{
  "name": "Duplicate check before writing (order forms to Google Sheets) v1.0",
  "nodes": [
    {
      "id": "6e781a8b-7463-4e79-9764-3074bc150077",
      "name": "How it works",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        -560,
        -260
      ],
      "parameters": {
        "content": "## Duplicate check before writing\n\nFree template from StanAutomate (stanautomate.co.za/workflows). Walkthrough on YouTube: @StanAutomate.\n\nReads order forms (PDF) from Gmail, has AI pick out the details, checks them with plain rules, then **looks before writing**:\n- **Same email again** (a rerun or retry, same message ID): skipped, one line on the Skipped tab.\n- **Different email, order ref already logged**: not written; goes to Needs a person with a pointer to the existing row, and you get an email.\n- **New**: logged to Orders.\n\n### Setup (about 10 minutes)\n1. Make a Google Sheet with three tabs:\n   - **Orders**: Received, Customer, Order ref, Product, Quantity, Delivery date, Check, Logged by, message_id\n   - **Needs a person**: the same, with Reason instead of Check, plus Existing row\n   - **Skipped**: Received, Customer, Order ref, message_id, Note\n2. Connect Gmail, Google Sheets and an AI model (any OpenAI-compatible chat model) in the nodes that ask for credentials.\n3. Pick your sheet in the four Google Sheets nodes.\n4. Edit the Gmail search in **Order form arrives** to match your order emails.\n5. Put your address in **Email the reason**.\n\n### Limits\n- Two runs that overlap can both see an order as new. Rare; an hourly count check catches it.\n- It relies on the order ref the AI read. A misread digit looks like a new order.\n- It reads the whole sheet each run: fine for a small business tracker, use a database at tens of thousands of rows.",
        "width": 520,
        "height": 820,
        "color": 7
      }
    },
    {
      "id": "829ffaaa-9162-4f94-af63-bac185ff24ca",
      "name": "Order form arrives",
      "type": "n8n-nodes-base.gmailTrigger",
      "typeVersion": 1.3,
      "position": [
        0,
        96
      ],
      "parameters": {
        "pollTimes": {
          "item": [
            {
              "mode": "everyMinute"
            }
          ]
        },
        "simple": false,
        "filters": {
          "q": "subject:\"Order form\" has:attachment newer_than:1d",
          "readStatus": "both"
        },
        "options": {
          "downloadAttachments": true,
          "dataPropertyAttachmentsPrefixName": "attachment_"
        }
      }
    },
    {
      "id": "2f291740-ec7c-4604-ad67-d6d64faa3293",
      "name": "Get the text from the PDF",
      "type": "n8n-nodes-base.extractFromFile",
      "typeVersion": 1.1,
      "position": [
        240,
        96
      ],
      "parameters": {
        "operation": "pdf",
        "binaryPropertyName": "attachment_0",
        "options": {
          "joinPages": true
        }
      }
    },
    {
      "id": "1e8e935a-e82b-43e7-bd7f-de19b12c8c9c",
      "name": "AI picks out the details",
      "type": "@n8n/n8n-nodes-langchain.informationExtractor",
      "typeVersion": 1.2,
      "position": [
        480,
        96
      ],
      "retryOnFail": true,
      "maxTries": 3,
      "waitBetweenTries": 5000,
      "parameters": {
        "text": "={{ $json.text }}",
        "schemaType": "fromAttributes",
        "attributes": {
          "attributes": [
            {
              "name": "customer",
              "type": "string",
              "description": "The ordering company or customer name, exactly as written. Empty string if not on the form.",
              "required": false
            },
            {
              "name": "orderRef",
              "type": "string",
              "description": "The order reference or PO number, exactly as written. Empty string if not on the form.",
              "required": false
            },
            {
              "name": "product",
              "type": "string",
              "description": "The product or item ordered. Empty string if not on the form.",
              "required": false
            },
            {
              "name": "quantity",
              "type": "string",
              "description": "The quantity ordered, digits only. Empty string if not on the form.",
              "required": false
            },
            {
              "name": "deliveryDate",
              "type": "string",
              "description": "The requested delivery date, written as DD/MM/YYYY. Empty string if the form gives no delivery date. Never use the order date, never guess.",
              "required": false
            }
          ]
        },
        "options": {
          "systemPromptTemplate": "You read order forms. Copy each value only if it is written on the form. If a value is not on the form, return an empty string for it. Never guess, never fill a gap with a different field."
        }
      }
    },
    {
      "id": "fd3f0e7f-ce14-4dee-9052-404d9fab103d",
      "name": "AI model",
      "type": "@n8n/n8n-nodes-langchain.lmChatOpenAi",
      "typeVersion": 1.3,
      "position": [
        528,
        320
      ],
      "parameters": {
        "model": {
          "__rl": true,
          "mode": "id",
          "value": "gpt-4o-mini"
        },
        "options": {
          "temperature": 0,
          "maxRetries": 2
        }
      }
    },
    {
      "id": "bfd358f9-f41b-4427-9b90-5e82e210f895",
      "name": "Check the details (plain rules)",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        800,
        96
      ],
      "parameters": {
        "mode": "runOnceForAllItems",
        "jsCode": "const now = $now.setZone('Africa/Johannesburg');\nconst today = now.startOf('day');\nconst emails = $('Order form arrives').all();\n// Accepts 11/12/2026 or 'Friday, 11 December 2026', and always writes DD/MM/YYYY.\nconst toDate = (v) => {\n  const t = v.replace(/\\.$/, '').trim();\n  let d = DateTime.fromFormat(t, 'dd/MM/yyyy', { zone: 'Africa/Johannesburg' });\n  if (!d.isValid) d = DateTime.fromFormat(t.replace(/^[A-Za-z]+,\\s*/, ''), 'd LLLL yyyy', { zone: 'Africa/Johannesburg', locale: 'en' });\n  return d;\n};\nreturn $input.all().map((item, i) => {\n  const f = item.json.output || {};\n  const s = (v) => String(v ?? '').trim();\n  const customer = s(f.customer), orderRef = s(f.orderRef), product = s(f.product);\n  const quantity = s(f.quantity);\n  let deliveryDate = s(f.deliveryDate);\n  const problems = [];\n  if (!customer) problems.push('customer missing');\n  if (!orderRef) problems.push('order reference missing');\n  if (!product) problems.push('product missing');\n  if (!/^\\d[\\d,]*$/.test(quantity)) problems.push('quantity is not a number');\n  if (!deliveryDate) problems.push('delivery date missing');\n  else {\n    const d = toDate(deliveryDate);\n    if (!d.isValid) problems.push('delivery date is not a real date');\n    else if (d < today) problems.push('delivery date is in the past');\n    else deliveryDate = d.toFormat('dd/MM/yyyy');\n  }\n  return { json: {\n    'Received': now.toFormat('dd/MM/yyyy'),\n    'Customer': customer,\n    'Order ref': orderRef,\n    'Product': product,\n    'Quantity': quantity,\n    'Delivery date': deliveryDate,\n    'Check': 'Checked',\n    'Reason': problems.join('; '),\n    'Logged by': 'Automation',\n    'message_id': emails[i].json.id,\n    allGood: problems.length === 0\n  } };\n});"
      }
    },
    {
      "id": "e078f1bf-1e90-4f8a-ba66-193a8569005a",
      "name": "Read the tracker",
      "type": "n8n-nodes-base.googleSheets",
      "typeVersion": 4.7,
      "position": [
        1040,
        96
      ],
      "parameters": {
        "resource": "sheet",
        "operation": "read",
        "documentId": {
          "__rl": true,
          "mode": "url",
          "value": ""
        },
        "sheetName": {
          "__rl": true,
          "mode": "name",
          "value": "Orders"
        },
        "options": {}
      },
      "retryOnFail": true,
      "maxTries": 3,
      "waitBetweenTries": 5000,
      "executeOnce": true,
      "alwaysOutputData": true
    },
    {
      "id": "088242ab-f847-41da-a023-d113a4249669",
      "name": "Read the Needs a person tab",
      "type": "n8n-nodes-base.googleSheets",
      "typeVersion": 4.7,
      "position": [
        1160,
        256
      ],
      "parameters": {
        "resource": "sheet",
        "operation": "read",
        "documentId": {
          "__rl": true,
          "mode": "url",
          "value": ""
        },
        "sheetName": {
          "__rl": true,
          "mode": "name",
          "value": "Needs a person"
        },
        "options": {}
      },
      "retryOnFail": true,
      "maxTries": 3,
      "waitBetweenTries": 5000,
      "executeOnce": true,
      "alwaysOutputData": true
    },
    {
      "id": "5b0820b9-e73f-47ce-9e27-140806d13488",
      "name": "Look before writing",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        1280,
        96
      ],
      "parameters": {
        "mode": "runOnceForAllItems",
        "jsCode": "// Optional: paste your sheet's link plus the Orders tab id, ending in range=A, so alerts link to the row.\n// Example: 'https://docs.google.com/spreadsheets/d/<sheet id>/edit#gid=<Orders tab id>&range=A'\nconst SHEET_URL = '';\n\n// Order refs are compared without spaces, dashes or capitals: 'PO 8012' = 'po-8012'.\nconst norm = (v) => String(v ?? '').toUpperCase().replace(/[^A-Z0-9]/g, '');\n\n// What is already in the tracker\nconst rows = $('Read the tracker').all().map((i) => i.json).filter((r) => r['Order ref'] || r.message_id);\n// Emails already sent to a person count as handled too\nconst held = $input.all().map((i) => i.json).filter((r) => r.message_id);\nconst seenEmail = new Map();\nconst seenRef = new Map();\nfor (const r of rows) {\n  if (r.message_id) seenEmail.set(String(r.message_id), r);\n  const k = norm(r['Order ref']);\n  if (k && !seenRef.has(k)) seenRef.set(k, r);\n}\nfor (const r of held) if (!seenEmail.has(String(r.message_id))) seenEmail.set(String(r.message_id), { ...r, tab: 'Needs a person' });\nconst where = (r) => (r.row_number ? (r.tab ? r.tab + ' row ' : 'row ') + r.row_number : 'earlier in this batch');\n\nreturn $('Check the details (plain rules)').all().map((item) => {\n  const o = { ...item.json, Note: '', 'Existing row': '' };\n  const id = String(o.message_id);\n  const ref = norm(o['Order ref']);\n\n  if (seenEmail.has(id)) {\n    // 1. Same email again (a rerun or a retry): never a new order, skip it\n    o.route = 'skip';\n    o.Note = 'Same email already handled (' + where(seenEmail.get(id)) + '), skipped';\n  } else if (ref && seenRef.has(ref)) {\n    // 2. Different email, order ref already logged: could be a resend, a correction or a reused number\n    const r = seenRef.get(ref);\n    o.route = 'person';\n    o.Reason = [o.Reason, 'order reference already logged (' + where(r) + ') from a different email'].filter(Boolean).join('; ');\n    if (r.row_number) o['Existing row'] = SHEET_URL ? SHEET_URL + r.row_number : 'Orders row ' + r.row_number;\n  } else if (!o.allGood) {\n    o.route = 'person';\n  } else {\n    o.route = 'log';\n  }\n\n  // Remember this one, so a second copy in the same batch is caught too\n  seenEmail.set(id, o);\n  if (ref && o.route === 'log') seenRef.set(ref, o);\n  return { json: o };\n});"
      }
    },
    {
      "id": "8762cb2d-d22d-4734-970a-3daad3761d52",
      "name": "New, repeat or doubt?",
      "type": "n8n-nodes-base.switch",
      "typeVersion": 3.2,
      "position": [
        1520,
        96
      ],
      "parameters": {
        "rules": {
          "values": [
            {
              "outputKey": "New order",
              "renameOutput": true,
              "conditions": {
                "options": {
                  "caseSensitive": true,
                  "leftValue": "",
                  "typeValidation": "strict"
                },
                "conditions": [
                  {
                    "leftValue": "={{ $json.route }}",
                    "operator": {
                      "type": "string",
                      "operation": "equals"
                    },
                    "rightValue": "log"
                  }
                ],
                "combinator": "and"
              }
            },
            {
              "outputKey": "Same email again",
              "renameOutput": true,
              "conditions": {
                "options": {
                  "caseSensitive": true,
                  "leftValue": "",
                  "typeValidation": "strict"
                },
                "conditions": [
                  {
                    "leftValue": "={{ $json.route }}",
                    "operator": {
                      "type": "string",
                      "operation": "equals"
                    },
                    "rightValue": "skip"
                  }
                ],
                "combinator": "and"
              }
            },
            {
              "outputKey": "Needs a person",
              "renameOutput": true,
              "conditions": {
                "options": {
                  "caseSensitive": true,
                  "leftValue": "",
                  "typeValidation": "strict"
                },
                "conditions": [
                  {
                    "leftValue": "={{ $json.route }}",
                    "operator": {
                      "type": "string",
                      "operation": "equals"
                    },
                    "rightValue": "person"
                  }
                ],
                "combinator": "and"
              }
            }
          ]
        },
        "options": {}
      }
    },
    {
      "id": "ce2a5d08-dba9-49a0-a9ce-9affc1de6aba",
      "name": "Log to the tracker",
      "type": "n8n-nodes-base.googleSheets",
      "typeVersion": 4.7,
      "position": [
        1780,
        -64
      ],
      "parameters": {
        "resource": "sheet",
        "operation": "append",
        "documentId": {
          "__rl": true,
          "mode": "url",
          "value": ""
        },
        "sheetName": {
          "__rl": true,
          "mode": "name",
          "value": "Orders"
        },
        "columns": {
          "mappingMode": "autoMapInputData",
          "value": {}
        },
        "options": {
          "cellFormat": "RAW",
          "handlingExtraData": "ignoreIt"
        }
      },
      "retryOnFail": true,
      "maxTries": 3,
      "waitBetweenTries": 5000
    },
    {
      "id": "c5bc257e-44fa-43a0-96ce-bf0fa244a6b5",
      "name": "Note the skip",
      "type": "n8n-nodes-base.googleSheets",
      "typeVersion": 4.7,
      "position": [
        1780,
        96
      ],
      "parameters": {
        "resource": "sheet",
        "operation": "append",
        "documentId": {
          "__rl": true,
          "mode": "url",
          "value": ""
        },
        "sheetName": {
          "__rl": true,
          "mode": "name",
          "value": "Skipped"
        },
        "columns": {
          "mappingMode": "autoMapInputData",
          "value": {}
        },
        "options": {
          "cellFormat": "RAW",
          "handlingExtraData": "ignoreIt"
        }
      },
      "retryOnFail": true,
      "maxTries": 3,
      "waitBetweenTries": 5000
    },
    {
      "id": "3d4160c3-b44d-4be1-b053-64bd7d88850d",
      "name": "Send to a person",
      "type": "n8n-nodes-base.googleSheets",
      "typeVersion": 4.7,
      "position": [
        1780,
        256
      ],
      "parameters": {
        "resource": "sheet",
        "operation": "append",
        "documentId": {
          "__rl": true,
          "mode": "url",
          "value": ""
        },
        "sheetName": {
          "__rl": true,
          "mode": "name",
          "value": "Needs a person"
        },
        "columns": {
          "mappingMode": "autoMapInputData",
          "value": {}
        },
        "options": {
          "cellFormat": "RAW",
          "handlingExtraData": "ignoreIt"
        }
      },
      "retryOnFail": true,
      "maxTries": 3,
      "waitBetweenTries": 5000
    },
    {
      "id": "02214abe-5a38-4e9f-a8aa-2f59f5f4d6e7",
      "name": "Email the reason",
      "type": "n8n-nodes-base.gmail",
      "typeVersion": 2.1,
      "position": [
        2020,
        256
      ],
      "retryOnFail": true,
      "maxTries": 3,
      "waitBetweenTries": 5000,
      "parameters": {
        "resource": "message",
        "operation": "send",
        "sendTo": "you@example.com",
        "subject": "=Needs a person: order {{ $json[\"Order ref\"] }} from {{ $json[\"Customer\"] }}",
        "emailType": "text",
        "message": "=Order {{ $json[\"Order ref\"] }} from {{ $json[\"Customer\"] }} was not logged.\nReason: {{ $json[\"Reason\"] }}.\n{{ $json[\"Existing row\"] ? \"The order already in the tracker: \" + $json[\"Existing row\"] + \"\\nPlease compare the two and decide.\" : \"Please check it and add it by hand.\" }}",
        "options": {
          "appendAttribution": false
        }
      }
    }
  ],
  "connections": {
    "Order form arrives": {
      "main": [
        [
          {
            "node": "Get the text from the PDF",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Get the text from the PDF": {
      "main": [
        [
          {
            "node": "AI picks out the details",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "AI model": {
      "ai_languageModel": [
        [
          {
            "node": "AI picks out the details",
            "type": "ai_languageModel",
            "index": 0
          }
        ]
      ]
    },
    "AI picks out the details": {
      "main": [
        [
          {
            "node": "Check the details (plain rules)",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Check the details (plain rules)": {
      "main": [
        [
          {
            "node": "Read the tracker",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Read the tracker": {
      "main": [
        [
          {
            "node": "Read the Needs a person tab",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Read the Needs a person tab": {
      "main": [
        [
          {
            "node": "Look before writing",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Look before writing": {
      "main": [
        [
          {
            "node": "New, repeat or doubt?",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "New, repeat or doubt?": {
      "main": [
        [
          {
            "node": "Log to the tracker",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Note the skip",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Send to a person",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Send to a person": {
      "main": [
        [
          {
            "node": "Email the reason",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  },
  "pinData": {},
  "settings": {
    "executionOrder": "v1"
  }
}
