{
  "name": "Social: bozze dei post ogni settimana",
  "nodes": [
    {
      "parameters": {
        "content": "## Social: bozze dei post ogni settimana\nOgni lunedì legge la tua **lista di argomenti** da un Google Sheet pubblicato come CSV, scrive le bozze dei post per le piattaforme che scegli e te le manda per email. **Pubblichi tu**, dopo averle rilette.\n\n**Il foglio:** colonne `argomento`, `note`, `stato`. Le righe con stato \"fatto\" o \"pubblicato\" vengono saltate. Pubblicalo con *File → Condividi → Pubblica sul web → CSV* e incolla il link in Impostazioni.\n\n**Credenziali da collegare dopo l'importazione**\n- **OpenAI** → nei nodi HTTP Request \"… con AI\": Header Auth con *Name* `Authorization` e *Value* `Bearer LA-TUA-CHIAVE`.\n- **Email (SMTP)** → nei nodi Send Email: l'account da cui partono i messaggi.\n\nPoi apri il nodo **Impostazioni** e cambia solo il blocco iniziale (email, attività, modello).\nFai una prova con *Execute workflow*, poi attivalo con *Publish* (in n8n 1.x: *Test workflow* e interruttore *Active*).",
        "width": 540,
        "height": 430,
        "color": 5
      },
      "id": "f9ff136e-4863-5991-add9-fe466bd81663",
      "name": "Leggimi",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        0,
        -250
      ]
    },
    {
      "parameters": {
        "rule": {
          "interval": [
            {
              "field": "weeks",
              "weeksInterval": 1,
              "triggerAtDay": [
                1
              ],
              "triggerAtHour": 8,
              "triggerAtMinute": 0
            }
          ]
        }
      },
      "id": "6c9ef27d-c358-53dd-a716-1f240969dc29",
      "name": "Ogni lunedì",
      "type": "n8n-nodes-base.scheduleTrigger",
      "typeVersion": 1.2,
      "position": [
        0,
        300
      ]
    },
    {
      "parameters": {
        "jsCode": "// ⚙️ IMPOSTAZIONI — modifica solo questo blocco\nconst cfg = {\n  csvUrl: 'https://docs.google.com/spreadsheets/d/e/IL-TUO-FOGLIO/pub?output=csv',\n  model: 'gpt-4o-mini',\n  tuaEmail: 'tu@esempio.it',\n  mittente: 'automazioni@esempio.it',\n  attivita: 'studio di consulenza per piccole imprese',\n  tono: 'diretto, concreto, niente frasi fatte',\n  piattaforme: ['LinkedIn', 'Instagram'],\n  quanti: 3,                            // quanti argomenti usare ogni settimana\n};\nreturn [{ json: { cfg } }];\n"
      },
      "id": "95186772-c133-55e7-ac72-5e37ed4a3249",
      "name": "Impostazioni",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        240,
        300
      ]
    },
    {
      "parameters": {
        "url": "={{ $json.cfg.csvUrl }}",
        "options": {
          "response": {
            "response": {
              "responseFormat": "text"
            }
          }
        }
      },
      "id": "2f251d7a-59a1-5976-a810-079bc56201a8",
      "name": "Leggi argomenti",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        480,
        300
      ]
    },
    {
      "parameters": {
        "jsCode": "// Legge un CSV (separatore , oppure ;) e restituisce un array di oggetti con\n// le intestazioni in minuscolo come chiavi.\nfunction parseCsv(text) {\n  text = String(text || '').replace(/^﻿/, '');\n  const first = text.split(/\\r?\\n/)[0] || '';\n  const delim = first.split(';').length > first.split(',').length ? ';' : ',';\n  const rows = []; let row = [], cell = '', q = false;\n  for (let i = 0; i < text.length; i++) {\n    const c = text[i];\n    if (q) {\n      if (c === '\"') { if (text[i + 1] === '\"') { cell += '\"'; i++; } else q = false; }\n      else cell += c;\n    } else if (c === '\"') q = true;\n    else if (c === delim) { row.push(cell); cell = ''; }\n    else if (c === '\\n' || c === '\\r') {\n      if (c === '\\r' && text[i + 1] === '\\n') i++;\n      row.push(cell); rows.push(row); row = []; cell = '';\n    } else cell += c;\n  }\n  if (cell !== '' || row.length) { row.push(cell); rows.push(row); }\n  const head = (rows.shift() || []).map(h => h.trim().toLowerCase());\n  return rows\n    .filter(r => r.some(v => v.trim() !== ''))\n    .map(r => Object.fromEntries(head.map((h, i) => [h, (r[i] || '').trim()])));\n}\n\nconst cfg = $('Impostazioni').first().json.cfg;\nconst righe = parseCsv($input.first().json.data)\n  .filter(r => r.argomento && !['fatto', 'pubblicato'].includes((r.stato || '').toLowerCase()))\n  .slice(0, cfg.quanti);\nreturn righe.map(r => ({ json: { argomento: r.argomento, body: {\n  model: cfg.model, temperature: 0.7, response_format: { type: 'json_object' },\n  messages: [\n    { role: 'system', content:\n      `Scrivi post social in italiano per: ${cfg.attivita}. Tono: ${cfg.tono}. ` +\n      `Un post per ciascuna piattaforma: ${cfg.piattaforme.join(', ')}, adattato al suo stile e alla sua lunghezza tipica. ` +\n      `Non inventare dati, numeri o clienti. Rispondi solo con un oggetto JSON: ` +\n      `{\"post\": [{\"piattaforma\": string, \"testo\": string, \"hashtag\": [string]}]}.` },\n    { role: 'user', content: `Argomento: ${r.argomento}\\nNote: ${r.note || '-'}` },\n  ],\n} } }));\n"
      },
      "id": "b7103979-85ac-57f1-ae73-b0773aaa6d41",
      "name": "Scegli argomenti",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        720,
        300
      ]
    },
    {
      "parameters": {
        "method": "POST",
        "url": "https://api.openai.com/v1/chat/completions",
        "authentication": "genericCredentialType",
        "genericAuthType": "httpHeaderAuth",
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={{ JSON.stringify($json.body) }}",
        "options": {}
      },
      "id": "f2df2230-e270-53a8-bdf7-029516668cbf",
      "name": "Scrivi bozze con AI",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        960,
        300
      ]
    },
    {
      "parameters": {
        "jsCode": "// Estrae il JSON dalla risposta di OpenAI; se non è valido restituisce `fallback`.\nfunction leggiAI(risposta, fallback) {\n  try { return JSON.parse(risposta.choices[0].message.content); } catch (e) { return fallback; }\n}\n\nconst cfg = $('Impostazioni').first().json.cfg;\nconst scelti = $('Scegli argomenti').all();\nconst blocchi = $input.all().map((item, i) => {\n  const r = leggiAI(item.json, { post: [] });\n  const post = (r.post || []).map(p =>\n    `[${p.piattaforma}]\\n${p.testo}\\n${(p.hashtag || []).map(h => h.startsWith('#') ? h : '#' + h).join(' ')}`);\n  return `■ ${scelti[i].json.argomento}\\n\\n${post.join('\\n\\n') || '(nessuna bozza generata)'}`;\n});\nconst testo = ['Ecco le bozze di questa settimana. Rileggile e adattale prima di pubblicarle.', '', blocchi.join('\\n\\n────────\\n\\n')].join('\\n');\nreturn [{ json: { oggetto: `Bozze post social — settimana del ${new Date().toLocaleDateString('it-IT')}`, testo, a: cfg.tuaEmail, da: cfg.mittente } }];\n"
      },
      "id": "026c4cc6-5dcb-566c-a57f-b43f3c3ea73c",
      "name": "Raccogli bozze",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        1200,
        300
      ]
    },
    {
      "parameters": {
        "fromEmail": "={{ $json.da }}",
        "toEmail": "={{ $json.a }}",
        "subject": "={{ $json.oggetto }}",
        "emailFormat": "text",
        "text": "={{ $json.testo }}",
        "options": {}
      },
      "id": "6d670368-8021-5580-bf48-e60a1e74cd78",
      "name": "Invia bozze a me",
      "type": "n8n-nodes-base.emailSend",
      "typeVersion": 2.1,
      "position": [
        1440,
        300
      ]
    }
  ],
  "connections": {
    "Ogni lunedì": {
      "main": [
        [
          {
            "node": "Impostazioni",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Impostazioni": {
      "main": [
        [
          {
            "node": "Leggi argomenti",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Leggi argomenti": {
      "main": [
        [
          {
            "node": "Scegli argomenti",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Scegli argomenti": {
      "main": [
        [
          {
            "node": "Scrivi bozze con AI",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Scrivi bozze con AI": {
      "main": [
        [
          {
            "node": "Raccogli bozze",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Raccogli bozze": {
      "main": [
        [
          {
            "node": "Invia bozze a me",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  },
  "active": false,
  "settings": {
    "executionOrder": "v1"
  },
  "pinData": {},
  "meta": {
    "templateCredsSetupCompleted": false
  },
  "tags": []
}
