{
  "author": {
    "address": "0x425E78375336d1938cf0eaE5c40aa86CbE1C2eBB",
    "signature": "9e6ba7318f5ef87dfbbf262772a66a7678969fe64f4ad552144129658b15487765ad607dec02800a1278a7d6e9582d2ecb24397db3bce0cab8da9a1bfa84e8f61c"
  },
  "available_to_orchestrator": true,
  "changelog": "Updated",
  "content_hash": "sha256:301252bc98c4a1a067b0f6a6b3b65c30b3230b95c3fa411b65a2b31f24875a5d",
  "created_at": "2026-10-15T20:13:30Z",
  "format": "osaurus.template",
  "format_version": 2,
  "id": "E5098C5C-294E-4966-B861-B72B70F948A5",
  "kind": "workflow",
  "name": "Scan & Track Tax Receipt Tool (New Zealand)",
  "requirements": {
    "folders": [
      {
        "access": "read",
        "help": "Where you keep receipt photos and PDFs. You can then submit a receipt by just its file name.",
        "hint": {
          "path": "e.g. Documents/Tax/Receipts"
        },
        "key": "receipts",
        "label": "Receipts folder"
      }
    ],
    "knowledge": [],
    "mcp_servers": [],
    "models": [
      {
        "locality": "local_only",
        "needs_tool_use": false,
        "preferred": "OsaurusAI/Qwen3.6-35B-A3B-mxfp4",
        "slot": "extractor",
        "strictness": "always"
      }
    ],
    "network": [],
    "notes": {},
    "permissions": [],
    "plugins": [
      "osaurus.vision"
    ],
    "secrets": [],
    "tools": [
      "file_copy"
    ]
  },
  "summary": "Reads a receipt photo or PDF on this Mac, pulls out vendor, date, total and GST, picks an NZ IRD expense category, and saves it to the receipts table.",
  "version": 3,
  "workflow": {
    "edges": [
      {
        "from": "extract",
        "to": "record"
      },
      {
        "from": "record",
        "to": "save"
      },
      {
        "from": "resolve",
        "to": "copy"
      },
      {
        "from": "copy",
        "to": "read"
      },
      {
        "from": "read",
        "to": "ocr_text"
      },
      {
        "from": "ocr_text",
        "to": "extract"
      }
    ],
    "examples": [
      {
        "input": {
          "note": "printer paper and ink for the home office",
          "receipt": "countdown_receipt.jpg"
        },
        "name": "Stationery receipt"
      },
      {
        "input": {
          "note": "groceries for company lunch",
          "receipt": "~/Downloads/IMG_2347.HEIC"
        },
        "name": "Woolworths company lunch"
      }
    ],
    "folders": [
      {
        "access": "read",
        "help": "Where you keep receipt photos and PDFs. You can then submit a receipt by just its file name.",
        "hint": {
          "path": "e.g. Documents/Tax/Receipts"
        },
        "key": "receipts",
        "label": "Receipts folder"
      }
    ],
    "input_schema": {
      "additionalProperties": false,
      "properties": {
        "note": {
          "description": "Optional: what it was for, e.g. 'client lunch with Acme' or 'home office chair'.",
          "title": "Note",
          "type": "string"
        },
        "receipt": {
          "description": "The receipt photo or PDF: attach it in chat, pick a file, or type a file name from your Receipts folder.",
          "format": "file",
          "title": "Receipt",
          "type": "string"
        }
      },
      "required": [
        "receipt"
      ],
      "type": "object",
      "x-order": [
        "receipt",
        "note"
      ]
    },
    "model_slots": [
      {
        "locality": "local_only",
        "needs_tool_use": false,
        "preferred": "OsaurusAI/Qwen3.6-35B-A3B-mxfp4",
        "slot": "extractor",
        "strictness": "always"
      }
    ],
    "nodes": [
      {
        "id": "read",
        "input": {
          "image_path": "{{nodes.resolve.output.copy_name}}",
          "recognition_level": "accurate"
        },
        "intent": "Pull text from the photo or PDF (OCR on this Mac).",
        "kind": "tool",
        "name": "Read receipt (OCR)",
        "output_schema": {},
        "retry": {
          "backoff_seconds": 2,
          "max_attempts": 2
        },
        "timeout": 120,
        "tool": {
          "name": "detect_text",
          "plugin": "osaurus.vision"
        }
      },
      {
        "id": "extract",
        "inference": {
          "instructions": "You read OCR text from a New Zealand receipt or tax invoice and return structured expense data for an NZ IRD tax return. OCR reading order is approximate: a label and its amount may be on different lines.\n\nRules:\n- vendor: the business that issued the receipt.\n- date: the transaction date as YYYY-MM-DD (NZ receipts use day/month/year). Empty string if not found.\n- total: the final amount paid including GST, as a number in NZD.\n- gst: the GST amount printed on the receipt if you can see one (OCR may misspell GST as 'GSI' or 'G5T'); otherwise 0. Do not calculate it; a later step checks GST.\n- gst_number: the vendor's GST number if printed (like 44-833-938), else empty string.\n- currency: 3-letter code, usually NZD.\n- category: the best NZ IRD business expense category from the allowed list. Use the person's note as a strong hint about purpose. 'Entertainment' for meals, drinks and hospitality with clients/staff; 'Low-value asset' for equipment under $1,000 excl. GST; 'Depreciable asset' for equipment $1,000 or more excl. GST; 'Personal (not deductible)' for clearly private purchases.\n- deductible_percent: 100 normally; 50 for Entertainment; 0 for Personal; for Home office, Motor vehicle or Phone & internet use 100 unless the note gives a business-use share.\n- line_items: short descriptions of the main items bought (at most 8).\n- confidence: high, medium or low depending on how legible and complete the receipt is.\n- notes: one short sentence explaining the category choice or anything missing.\n\nIf the text is empty or is not a receipt, return vendor 'Unknown vendor', total 0, gst 0, category 'Other business expense', confidence 'low', and say so in notes.",
          "mode": "generate",
          "model_slot": "extractor",
          "temperature": 0
        },
        "input": {
          "note": "{{input.note}}",
          "receipt_text": "{{nodes.ocr_text.output.text}}"
        },
        "intent": "Local model finds vendor, date, totals, GST and IRD category.",
        "kind": "inference",
        "name": "Extract & categorise",
        "output_schema": {
          "additionalProperties": false,
          "properties": {
            "category": {
              "enum": [
                "Accounting & legal",
                "Advertising & marketing",
                "Bank fees & interest",
                "Computer & software",
                "Depreciable asset",
                "Low-value asset",
                "Entertainment",
                "Home office",
                "Insurance",
                "Motor vehicle",
                "Office supplies & stationery",
                "Phone & internet",
                "Professional development & subscriptions",
                "Rent & lease",
                "Repairs & maintenance",
                "Travel & accommodation",
                "Utilities",
                "Contractors & wages",
                "Other business expense",
                "Personal (not deductible)"
              ],
              "type": "string"
            },
            "confidence": {
              "enum": [
                "high",
                "medium",
                "low"
              ],
              "type": "string"
            },
            "currency": {
              "type": "string"
            },
            "date": {
              "type": "string"
            },
            "deductible_percent": {
              "type": "number"
            },
            "gst": {
              "type": "number"
            },
            "gst_number": {
              "type": "string"
            },
            "line_items": {
              "items": {
                "type": "string"
              },
              "type": "array"
            },
            "notes": {
              "type": "string"
            },
            "total": {
              "type": "number"
            },
            "vendor": {
              "type": "string"
            }
          },
          "required": [
            "vendor",
            "date",
            "total",
            "gst",
            "gst_number",
            "currency",
            "category",
            "deductible_percent",
            "line_items",
            "confidence",
            "notes"
          ],
          "type": "object"
        },
        "retry": {
          "backoff_seconds": 3,
          "max_attempts": 2
        },
        "timeout": 400
      },
      {
        "code": {
          "network": [],
          "secrets": [],
          "source": "async function run(input, ctx) {\n  const e = input.e || {};\n  const text = String(input.text || '');\n  const lines = text.split(/\\r?\\n/);\n  const r2 = n => Math.round((Number(n) || 0) * 100) / 100;\n  const near = (a, b, tol) => Math.abs(a - b) <= (tol == null ? 0.02 : tol);\n  const amounts = s => { const out = []; const re = /(\\d{1,3}(?:,\\d{3})+|\\d+)\\.(\\d{2})(?!\\d)/g; let m; while ((m = re.exec(s))) out.push(r2(m[1].replace(/,/g, '') + '.' + m[2])); return out; };\n  const all = amounts(text);\n  const total = r2(e.total);\n  const pct = Math.max(0, Math.min(100, Number(e.deductible_percent) || 0));\n  const vendor = (e.vendor || 'Unknown vendor').trim();\n  const date = (e.date || '').trim();\n  const checks = [];\n  let needs_review = false;\n  const gstWord = /\\bG\\s?[S5]\\s?[TIl1]\\b/i;\n  let gst_number = (e.gst_number || '').trim();\n  if (!gst_number) { const m = /\\bG\\s?[S5]\\s?[TIl1]\\b[^\\d\\n]{0,20}(\\d{2,3}[- ]?\\d{3}[- ]?\\d{3})/i.exec(text); if (m) gst_number = m[1]; }\n  const isNumberLine = l => /\\d{2,3}[- ]\\d{3}[- ]\\d{3}/.test(l);\n  const gstLines = [];\n  lines.forEach((l, i) => { if (gstWord.test(l) && !isNumberLine(l)) gstLines.push(i); });\n  const inclStated = gstLines.some(i => /incl|includ|inclusive/i.test(lines[i]));\n  const taxInvoice = /tax\\s*invoice/i.test(text);\n  const declared = inclStated || !!gst_number || taxInvoice || gstLines.length > 0;\n  const expected = r2(total * 3 / 23);\n  const sameLine = [], adjacent = [];\n  gstLines.forEach(i => {\n    amounts(lines[i]).forEach(a => { if (a > 0 && a < total) sameLine.push(a); });\n    [i - 1, i + 1].forEach(j => { if (lines[j] != null) amounts(lines[j]).forEach(a => { if (a > 0 && a < total) adjacent.push(a); }); });\n  });\n  let gst = 0, gst_status;\n  const nearGst = sameLine.concat(adjacent).find(a => near(a, expected));\n  const anywhere = all.find(a => near(a, expected) && !near(a, total, 0.005));\n  const statedOther = sameLine.find(a => a <= expected + 0.02);\n  if (total <= 0) {\n    gst_status = 'no_total'; needs_review = true;\n    checks.push('Could not read a total, so GST could not be checked.');\n  } else if (declared && nearGst != null) {\n    gst = nearGst; gst_status = 'verified';\n    checks.push(`GST $${gst.toFixed(2)} is stated on the receipt and matches 15% of $${total.toFixed(2)}.`);\n  } else if (statedOther != null) {\n    gst = statedOther; gst_status = 'stated_differs'; needs_review = true;\n    checks.push(`Receipt states GST $${gst.toFixed(2)}, but 15% of the total would be $${expected.toFixed(2)}; some items may be GST-free. Used the stated figure.`);\n  } else if (declared && anywhere != null) {\n    gst = anywhere; gst_status = 'found_on_receipt';\n    checks.push(`GST is declared and $${gst.toFixed(2)} (15% of the total) appears on the receipt, though not on a labelled GST line.`);\n  } else if (declared) {\n    gst = expected; gst_status = 'calculated_not_found'; needs_review = true;\n    checks.push(`Receipt declares GST${gst_number ? ' (GST No. ' + gst_number + ')' : ''} but $${expected.toFixed(2)} was not found on it; filled in at 15%. Check the receipt.`);\n  } else {\n    gst = 0; gst_status = 'not_declared'; needs_review = true;\n    checks.push('No GST statement or GST number found on the receipt; recorded with no GST. Check the receipt.');\n  }\n  if (total > 0 && !all.some(a => near(a, total, 0.005))) { needs_review = true; checks.push(`The total $${total.toFixed(2)} does not appear in the receipt text.`); }\n  if (!date) { needs_review = true; checks.push('No date found.'); }\n  if (e.confidence === 'low') needs_review = true;\n  const gst_check = checks.join(' ');\n  const raw = [date, vendor.toLowerCase(), total.toFixed(2)].join('|');\n  let h = 2166136261;\n  for (let i = 0; i < raw.length; i++) { h ^= raw.charCodeAt(i); h = Math.imul(h, 16777619); }\n  const id = (date || 'nodate') + '-' + (h >>> 0).toString(16).padStart(8, '0');\n  const excl = r2(total - gst);\n  const tax_year = (() => { const m = /^(\\d{4})-(\\d{2})/.exec(date); if (!m) return ''; const y = +m[1], mo = +m[2]; const end = mo >= 4 ? y + 1 : y; return (end - 1) + '-' + String(end).slice(2); })();\n  const record = { id, vendor, date, tax_year, total, gst, gst_status, gst_check, needs_review, total_excl_gst: excl, gst_number, currency: e.currency || 'NZD', category: e.category, deductible_percent: pct, claimable_excl_gst: r2(excl * pct / 100), claimable_gst: r2(gst * pct / 100), line_items: e.line_items || [], note: input.note || '', confidence: e.confidence, model_notes: e.notes || '', source_file: input.file || '', submitted_at: new Date().toISOString() };\n  const summary = `${vendor} ${date || '(no date)'} $${total.toFixed(2)} incl. GST $${gst.toFixed(2)} [${gst_status}] → ${e.category} (${pct}% deductible, tax year ${tax_year || '?'})${needs_review ? ' — NEEDS REVIEW: ' + gst_check : ''}`;\n  return { id, record, summary };\n}",
          "timeout": 30
        },
        "id": "record",
        "input": {
          "e": "{{nodes.extract.output}}",
          "file": "{{nodes.resolve.output.source}}",
          "note": "{{input.note}}",
          "text": "{{nodes.ocr_text.output.text}}"
        },
        "intent": "Make a stable ID and tidy the row.",
        "kind": "code",
        "name": "Check GST & build record",
        "output_schema": {
          "properties": {
            "id": {
              "type": "string"
            },
            "record": {
              "type": "object"
            },
            "summary": {
              "type": "string"
            }
          },
          "required": [
            "id",
            "record",
            "summary"
          ],
          "type": "object"
        },
        "retry": {
          "backoff_seconds": 1,
          "max_attempts": 1
        },
        "timeout": 120
      },
      {
        "id": "save",
        "input": {},
        "intent": "Store in the workflow's receipts table.",
        "kind": "state",
        "name": "Save to receipts table",
        "output_schema": {},
        "retry": {
          "backoff_seconds": 1,
          "max_attempts": 1
        },
        "state": {
          "action": "set",
          "key": "{{nodes.record.output.id}}",
          "table": "receipts",
          "value": "{{nodes.record.output.record}}"
        },
        "timeout": 120
      },
      {
        "code": {
          "network": [],
          "secrets": [],
          "source": "async function run(input, ctx) {\n  let p = String(input.file || '').trim();\n  if (!p) throw new Error('No receipt file was given.');\n  if (p.startsWith('file://')) p = decodeURIComponent(p.slice(7));\n  const absolute = p.startsWith('/') || p.startsWith('~');\n  if (!absolute) {\n    if (!input.folder) throw new Error('\"' + p + '\" is a file name, but no Receipts folder is set up. Pass the full file or set the folder in Set Up.');\n    p = String(input.folder).replace(/\\/$/, '') + '/' + p;\n  }\n  const m = /\\.([A-Za-z0-9]+)$/.exec(p);\n  const ext = m ? m[1].toLowerCase() : 'jpg';\n  return { source: p, copy_name: 'receipt-' + String(ctx.run.id).slice(0, 8) + '.' + ext };\n}",
          "timeout": 30
        },
        "id": "resolve",
        "input": {
          "file": "{{input.receipt}}",
          "folder": "{{folders.receipts}}"
        },
        "kind": "code",
        "name": "Find the file",
        "output_schema": {
          "additionalProperties": false,
          "properties": {
            "copy_name": {
              "type": "string"
            },
            "source": {
              "type": "string"
            }
          },
          "required": [
            "source",
            "copy_name"
          ],
          "type": "object"
        },
        "retry": {
          "backoff_seconds": 1,
          "max_attempts": 1
        },
        "timeout": 120
      },
      {
        "id": "copy",
        "input": {
          "destination": "{{nodes.resolve.output.copy_name}}",
          "source": "{{nodes.resolve.output.source}}"
        },
        "kind": "tool",
        "name": "Copy receipt in",
        "output_schema": {},
        "retry": {
          "backoff_seconds": 1,
          "max_attempts": 1
        },
        "timeout": 120,
        "tool": {
          "name": "file_copy"
        }
      },
      {
        "code": {
          "network": [],
          "secrets": [],
          "source": "async function run(input, ctx) {\n  const o = input.o;\n  if (typeof o === 'string') return { text: o, blocks: o ? o.split('\\n').length : 0 };\n  const blocks = [];\n  const walk = v => {\n    if (Array.isArray(v)) v.forEach(walk);\n    else if (v && typeof v === 'object') {\n      if (typeof v.text === 'string' && !Array.isArray(v.blocks)) blocks.push(v.text);\n      else Object.values(v).forEach(walk);\n    }\n  };\n  walk(o);\n  ctx.log('OCR shape sample: ' + JSON.stringify(o).slice(0, 600));\n  return { text: blocks.join('\\n'), blocks: blocks.length };\n}",
          "timeout": 30
        },
        "id": "ocr_text",
        "input": {
          "o": "{{nodes.read.output}}"
        },
        "kind": "code",
        "name": "Tidy text",
        "output_schema": {
          "additionalProperties": false,
          "properties": {
            "blocks": {
              "type": "number"
            },
            "text": {
              "type": "string"
            }
          },
          "required": [
            "text",
            "blocks"
          ],
          "type": "object"
        },
        "retry": {
          "backoff_seconds": 1,
          "max_attempts": 1
        },
        "timeout": 120
      }
    ],
    "output": {
      "category": "{{nodes.record.output.record.category}}",
      "date": "{{nodes.record.output.record.date}}",
      "deductible_percent": "{{nodes.record.output.record.deductible_percent}}",
      "gst": "{{nodes.record.output.record.gst}}",
      "gst_check": "{{nodes.record.output.record.gst_check}}",
      "gst_status": "{{nodes.record.output.record.gst_status}}",
      "needs_review": "{{nodes.record.output.record.needs_review}}",
      "receipt_id": "{{nodes.record.output.id}}",
      "summary": "{{nodes.record.output.summary}}",
      "total": "{{nodes.record.output.record.total}}",
      "vendor": "{{nodes.record.output.record.vendor}}"
    },
    "output_schema": {
      "additionalProperties": false,
      "properties": {
        "category": {
          "title": "IRD category",
          "type": "string"
        },
        "date": {
          "title": "Date",
          "type": "string"
        },
        "deductible_percent": {
          "title": "Deductible %",
          "type": "number"
        },
        "gst": {
          "title": "GST",
          "type": "number"
        },
        "gst_check": {
          "title": "GST check detail",
          "type": "string"
        },
        "gst_status": {
          "enum": [
            "verified",
            "found_on_receipt",
            "stated_differs",
            "calculated_not_found",
            "not_declared",
            "no_total"
          ],
          "title": "GST check",
          "type": "string"
        },
        "needs_review": {
          "title": "Needs review",
          "type": "boolean"
        },
        "receipt_id": {
          "title": "Receipt ID",
          "type": "string"
        },
        "summary": {
          "title": "Summary",
          "type": "string"
        },
        "total": {
          "title": "Total (incl. GST)",
          "type": "number"
        },
        "vendor": {
          "title": "Vendor",
          "type": "string"
        }
      },
      "required": [
        "receipt_id",
        "vendor",
        "date",
        "total",
        "gst",
        "gst_status",
        "gst_check",
        "needs_review",
        "category",
        "deductible_percent",
        "summary"
      ],
      "type": "object"
    },
    "requirement_notes": {},
    "secrets": []
  }
}