{
  "nodes": [
    {
      "parameters": {
        "url": "https://transfer-superstars.myshopify.com/admin/api/2023-10/orders.json",
        "authentication": "predefinedCredentialType",
        "nodeCredentialType": "shopifyAccessTokenApi",
        "sendQuery": true,
        "queryParameters": {
          "parameters": [
            {
              "name": "limit",
              "value": "10"
            },
            {
              "name": "status",
              "value": "any"
            },
            {
              "name": "created_at_min",
              "value": "={{ $now.minus(2, 'day').toISO() }}"
            },
            {
              "name": "order",
              "value": "created_at desc"
            }
          ]
        },
        "options": {}
      },
      "id": "4c6e5ed0-4f13-4b5e-98c2-ddb8c08d4d42",
      "name": "Shopify HTTP",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4,
      "position": [
        -1580,
        -420
      ],
      "credentials": {
        "shopifyAccessTokenApi": {
          "name": "<your credential>"
        }
      },
      "onError": "continueRegularOutput"
    },
    {
      "parameters": {
        "fieldToSplitOut": "orders",
        "options": {}
      },
      "id": "93de4b83-572d-4596-a455-f6a2ff14013b",
      "name": "Split Orders",
      "type": "n8n-nodes-base.itemLists",
      "typeVersion": 1,
      "position": [
        -1380,
        -420
      ],
      "onError": "continueRegularOutput"
    },
    {
      "parameters": {
        "numberInputs": 3
      },
      "id": "ea553eb9-8979-4d7d-af5a-b3298fab7831",
      "name": "Merge \u2192 Combine",
      "type": "n8n-nodes-base.merge",
      "typeVersion": 3,
      "position": [
        -680,
        -100
      ],
      "onError": "continueRegularOutput"
    },
    {
      "parameters": {
        "jsCode": "// Enhanced Source Detection and Shipment Preparation\nconst items = $input.all();\n\nreturn items.map(item => {\n  const d = item.json;\n  \n  // More robust source detection with additional checks\n  let source = 'unknown';\n  let shipmentData = {};\n  \n  // Shopify Detection\n  if (d.line_items && Array.isArray(d.line_items)) {\n    source = 'shopify';\n    \n    // Extract Shopify-specific shipment data\n    shipmentData = {\n      orderId: d.name || d.id,\n      orderNumber: d.order_number,\n      fulfillmentStatus: d.fulfillment_status,\n      shippingAddress: d.shipping_address,\n      customer: {\n        email: d.email || d.customer?.email,\n        name: d.shipping_address?.name || `${d.customer?.first_name} ${d.customer?.last_name}`,\n        phone: d.shipping_address?.phone || d.customer?.phone\n      },\n      items: d.line_items?.map(item => ({\n        name: item.name,\n        quantity: item.quantity,\n        sku: item.sku,\n        variant: item.variant_title\n      })),\n      financial: {\n        subtotal: parseFloat(d.subtotal_price || 0),\n        shipping: parseFloat(d.total_shipping_price_set?.shop_money?.amount || 0),\n        tax: parseFloat(d.total_tax || 0),\n        total: parseFloat(d.total_price || 0)\n      }\n    };\n  }\n  \n  // JotForm Detection\n  else if (d.answers && typeof d.answers === 'object') {\n    source = 'jotform';\n    \n    // Extract JotForm-specific shipment data\n    shipmentData = {\n      orderId: d.submissionID || d.id,\n      submissionId: d.submissionID,\n      customer: {\n        email: d.answers?.email?.answer || d.email,\n        name: d.answers?.name?.answer || '',\n        phone: d.answers?.phone?.answer || ''\n      },\n      shippingAddress: {\n        // Parse from JotForm address fields if available\n        name: d.answers?.shippingName?.answer || d.answers?.name?.answer,\n        address1: d.answers?.address?.answer?.addr_line1,\n        address2: d.answers?.address?.answer?.addr_line2,\n        city: d.answers?.address?.answer?.city,\n        state: d.answers?.address?.answer?.state,\n        zip: d.answers?.address?.answer?.postal,\n        country: d.answers?.address?.answer?.country || 'US'\n      },\n      items: [], // Would need to parse from form answers\n      financial: {\n        total: parseFloat(d.answers?.total?.answer || 0)\n      }\n    };\n  }\n  \n  // Jiffy Email Detection (enhanced with your preprocessing data)\n  else if (d.orderId && d.orderId.startsWith('JIFFY-')) {\n    source = 'jiffy';\n    \n    // Use the preprocessed Jiffy data structure\n    shipmentData = {\n      orderId: d.orderId,\n      poNumber: d.poNumber || d.jiffyPoNumber,\n      orderType: d.orderType,\n      rushService: d.rushService,\n      customer: d.customer,\n      shippingAddress: d.shipping,\n      shippingDate: d.shippingDate,\n      items: d.items,\n      financial: d.financial,\n      \n      // Critical shipping label info\n      shippingLabel: d.shippingLabel,\n      shipping_label_url: d.shipping_label_url || d.shipping_label_google_drive,\n      \n      // File information\n      files: d.files,\n      gangSheetUrls: d.gangSheetUrls,\n      cutlineReferences: d.cutlineReferences,  // ADDED: Cutline references\n      \n      // Status\n      paymentStatus: d.paymentStatus,\n      fileStatus: d.fileStatus\n    };\n  }\n  \n  // Legacy Jiffy detection (for emails not yet preprocessed)\n  else if (d.id && (d.subject || d.snippet || d.text) && \n           (d.subject?.includes('Jiffy') || d.from?.includes('jiffy'))) {\n    source = 'jiffy';\n    \n    // Basic shipment data from raw email\n    shipmentData = {\n      orderId: `JIFFY-${Date.now()}`,\n      emailId: d.id,\n      subject: d.subject,\n      requiresProcessing: true\n    };\n  }\n  \n  // Additional source detection patterns\n  else if (d.source) {\n    // If source is already defined, use it\n    source = d.source;\n    shipmentData = {\n      orderId: d.orderId || d.id,\n      ...d // Include all existing data\n    };\n  }\n  \n  // Build the final output structure\n  return {\n    json: {\n      // Root level source\n      source: source,\n      \n      // Shipment-ready data\n      shipment: {\n        source: source,\n        sourceData: shipmentData,\n        \n        // Common fields across all sources\n        orderId: shipmentData.orderId,\n        customer: shipmentData.customer || {},\n        shippingAddress: shipmentData.shippingAddress || {},\n        items: shipmentData.items || [],\n        financial: shipmentData.financial || {},\n        \n        // Shipping specific\n        shippingLabel: shipmentData.shippingLabel,\n        shipping_label_url: shipmentData.shipping_label_url,\n        rushService: shipmentData.rushService,\n        \n        // File information - ADDED cutlineReferences\n        files: shipmentData.files,\n        gangSheetUrls: shipmentData.gangSheetUrls,\n        cutlineReferences: shipmentData.cutlineReferences,\n        \n        // Meta\n        createdAt: new Date().toISOString(),\n        requiresProcessing: shipmentData.requiresProcessing || false\n      },\n      \n      // Original payload for reference\n      payload: d,\n      \n      // Additional metadata\n      meta: {\n        processedAt: new Date().toISOString(),\n        hasShippingLabel: !!shipmentData.shipping_label_url,\n        hasCutlineReferences: !!(shipmentData.cutlineReferences && shipmentData.cutlineReferences.length > 0),\n        isReadyForShipment: !!(shipmentData.orderId && shipmentData.shippingAddress)\n      }\n    },\n    \n    // Preserve binary data if exists\n    binary: item.binary\n  };\n});"
      },
      "id": "51338e60-2c91-4dd9-9847-e32be5379211",
      "name": "Function - Detect Source",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        -500,
        -100
      ]
    },
    {
      "parameters": {
        "dataType": "string",
        "value1": "={{ $json.source }}",
        "rules": {
          "rules": [
            {
              "value2": "shopify"
            },
            {
              "value2": "jotform",
              "output": 1
            },
            {
              "value2": "jiffy",
              "output": 2
            }
          ]
        },
        "fallbackOutput": 3
      },
      "id": "049fa0dd-400e-402e-ae2f-2600ec25d504",
      "name": "Switch",
      "type": "n8n-nodes-base.switch",
      "typeVersion": 1,
      "position": [
        -320,
        -120
      ]
    },
    {
      "parameters": {
        "jsCode": "// Helper function to format addresses with proper title case\nfunction formatAddress(address) {\n  if (!address) return '';\n  \n  // Replace line breaks with comma and space, clean up extra spaces\n  const cleaned = address\n    .replace(/\\r?\\n/g, ', ')  // Replace line breaks with comma\n    .replace(/,\\s*,/g, ',')   // Remove duplicate commas\n    .replace(/\\s+/g, ' ')     // Replace multiple spaces with single space\n    .trim();\n  \n  const states = ['AL','AK','AZ','AR','CA','CO','CT','DE','FL','GA','HI','ID','IL','IN','IA','KS','KY','LA','ME','MD','MA','MI','MN','MS','MO','MT','NE','NV','NH','NJ','NM','NY','NC','ND','OH','OK','OR','PA','RI','SC','SD','TN','TX','UT','VT','VA','WA','WV','WI','WY','DC'];\n  \n  return cleaned.split(/\\b/).map(part => {\n    const word = part.trim();\n    if (!word || /^[,\\s]+$/.test(part)) return part;\n    \n    // Keep state codes uppercase\n    if (states.includes(word.toUpperCase())) {\n      return word.toUpperCase();\n    }\n    \n    // Keep ZIP codes as-is\n    if (/^\\d{5}(-\\d{4})?$/.test(word)) {\n      return word;\n    }\n    \n    // Title case other words\n    if (/^[a-zA-Z]+$/.test(word)) {\n      return word.charAt(0).toUpperCase() + word.slice(1).toLowerCase();\n    }\n    \n    return word;\n  }).join('');\n}\n\n// Helper function to create formatted full address\nfunction createFullAddress(addressObj) {\n  if (!addressObj) return '';\n  \n  const parts = [\n    addressObj.address1,\n    addressObj.address2,\n    addressObj.city,\n    addressObj.province_code || addressObj.state,\n    addressObj.zip\n  ].filter(Boolean);\n  \n  return formatAddress(parts.join(', '));\n}\n\n// Helper function to extract filename from URL\nfunction extractFilenameFromUrl(url) {\n  if (!url) return '';\n  \n  try {\n    // Extract the last part of the URL path\n    const urlParts = url.split('/');\n    const filename = urlParts[urlParts.length - 1];\n    \n    // Remove query parameters if present\n    return filename.split('?')[0] || '';\n  } catch (e) {\n    return '';\n  }\n}\n\n// Helper function to determine if title is a default product name\nfunction isDefaultProductTitle(title) {\n  if (!title) return false;\n  \n  const defaultTitles = [\n    'DTF Transfer Online Gang Sheet Builder PRO For Clothing',\n    'DTF Transfer Online Gang Sheet Builder PRO',\n    'Gang Sheet Builder',\n    'DTF Online Builder',\n    'Online Gang Sheet Builder',\n    'UV Sticker Online Gang Sheet Builder',\n    'UV Online Builder',\n    'Sublimation Transfer Builder',\n    'Heat Press Builder',\n    'Custom Transfer Builder',\n    'Online Transfer Builder',\n    'Transfer Builder PRO',\n    'Custom Gang Sheet Builder'\n  ];\n  \n  return defaultTitles.some(defaultTitle => \n    title.toLowerCase().includes(defaultTitle.toLowerCase())\n  );\n}\n\n// Enhanced product type detection based on Airtable schema\nfunction detectProductType(lineItem) {\n  const title = (lineItem.title || '').toLowerCase();\n  const sku = (lineItem.sku || '').toLowerCase();\n  const variantTitle = (lineItem.variant_title || '').toLowerCase();\n  const properties = lineItem.properties || [];\n  \n  // Check if it's a sample pack first\n  if (isSamplePackItem(lineItem)) {\n    return 'Sample Pack';\n  }\n  \n  // Check properties for product type\n  const productTypeProp = properties.find(p => \n    p.name && p.name.toLowerCase() === 'product type'\n  );\n  if (productTypeProp && productTypeProp.value) {\n    // Map to exact Airtable values\n    const typeMap = {\n      'dtf': 'DTF Transfers',\n      'dtf gang sheet': 'DTF Gang Sheet',\n      'uv gang sheet': 'UV Gang Sheet',\n      'gang sheet': 'Gang Sheet', // Generic gang sheet\n      'uv': 'UV Stickers',\n      'sublimation': 'Sublimation',\n      'heat press': 'Heat Press',\n      'heat tape': 'Heat Tape',\n      'matt finishing': 'Matt Finishing Sheet',\n      'matt finishing sheet': 'Matt Finishing Sheet',\n      'laser alignment': 'Laser Alignment',\n      'alignment tool': 'Alignment Tool',\n      'accessories': 'Accessories',\n      'dtf + uv': 'DTF + UV DTF',\n      'sample': 'Sample Pack',\n      'sample pack': 'Sample Pack'\n    };\n    \n    const propValue = productTypeProp.value.toLowerCase();\n    for (const [key, value] of Object.entries(typeMap)) {\n      if (propValue.includes(key)) return value;\n    }\n  }\n  \n  // Special handling for Gang Sheet Builder products\n  if (title.includes('gang sheet builder')) {\n    // Check if it's UV or DTF gang sheet\n    if (title.includes('uv')) {\n      return 'UV Gang Sheet';\n    } else {\n      // Default gang sheet builder products to DTF\n      return 'DTF Gang Sheet';\n    }\n  }\n  \n  // Check for specific product types in title/SKU\n  if (title.includes('laser alignment') || sku.includes('laser-align')) return 'Laser Alignment';\n  if (title.includes('alignment tool') || sku.includes('align-tool')) return 'Alignment Tool';\n  if (title.includes('matt finishing') || title.includes('matte finishing')) return 'Matt Finishing Sheet';\n  if (title.includes('heat tape') || sku.includes('heat-tape')) return 'Heat Tape';\n  if (title.includes('uv') && title.includes('dtf')) return 'DTF + UV DTF';\n  if (title.includes('uv') && title.includes('gang')) return 'UV Gang Sheet';\n  if (title.includes('dtf') && title.includes('gang')) return 'DTF Gang Sheet';\n  if (title.includes('uv') || sku.includes('uv')) return 'UV Stickers';\n  if (title.includes('sublimation') || sku.includes('sublimation')) return 'Sublimation';\n  if (title.includes('heat press') || title.includes('heat-press')) return 'Heat Press';\n  if (title.includes('gang sheet') || sku.includes('gang')) {\n    // Generic gang sheet - check other clues\n    if (variantTitle.includes('uv')) return 'UV Gang Sheet';\n    return 'DTF Gang Sheet'; // Default to DTF\n  }\n  if (title.includes('accessory') || title.includes('accessories')) return 'Accessories';\n  \n  // Check variant title\n  if (variantTitle.includes('uv')) return 'UV Stickers';\n  if (variantTitle.includes('gang')) {\n    if (variantTitle.includes('uv')) return 'UV Gang Sheet';\n    return 'DTF Gang Sheet';\n  }\n  \n  // Default to DTF Transfers\n  return 'DTF Transfers';\n}\n\n// Determine facility based on order data\nfunction determineFacility(order, lineItems) {\n  // For Shopify orders, leave facility blank for user selection\n  return null;\n}\n\n// Helper function to determine if order needs files\nfunction orderNeedsFiles(lineItems) {\n  if (!Array.isArray(lineItems)) return false;\n  \n  return lineItems.some(li => {\n    // Sample packs don't need files\n    if (isSamplePackItem(li)) return false;\n    \n    const properties = li.properties || [];\n    const hasOriginal = properties.find(p => p.name === '_original_image');\n    const hasDpi300 = properties.find(p => p.name === '_dpi300_image');\n    const hasPrintReady = properties.find(p => p.name === '_Print Ready File');\n    return !hasOriginal && !hasDpi300 && !hasPrintReady;\n  });\n}\n\n// Helper function to check if item is a sample pack\nfunction isSamplePackItem(lineItem) {\n  const title = (lineItem.title || '').toLowerCase();\n  const sku = (lineItem.sku || '').toLowerCase();\n  const variantTitle = (lineItem.variant_title || '').toLowerCase();\n  \n  return title.includes('sample') || \n         title.includes('sample pack') || \n         title.includes('swatch') ||\n         sku.includes('sample') ||\n         sku.includes('sample-pack') ||\n         variantTitle.includes('sample');\n}\n\n// Helper function to check if order is sample pack only\nfunction isSamplePackOnlyOrder(lineItems, shippingAmount) {\n  if (!Array.isArray(lineItems) || lineItems.length === 0) return false;\n  \n  // Check if ALL items are sample packs\n  const allItemsAreSamples = lineItems.every(item => isSamplePackItem(item));\n  \n  // Check if shipping is $2\n  const hasLowShipping = shippingAmount === 2 || shippingAmount === 2.00;\n  \n  return allItemsAreSamples && hasLowShipping;\n}\n\n// Process ALL items\nconst items = $input.all();\nconst allOutputs = [];\n\nitems.forEach(item => {\n  try {\n    const order = item.json.payload;\n    \n    // Validate order structure\n    if (!order || typeof order !== 'object') {\n      throw new Error('Invalid order structure');\n    }\n\n    // UPDATED: Format IDs according to new requirements\n    // Extract the TSS number from order.name (e.g., \"#TSS9183\" -> \"TSS9183\")\n    const tssNumber = (order.name || '').replace('#', '').trim();\n    \n    // orderId: 'TS-TSS9183' format\n    const orderId = tssNumber ? `TS-${tssNumber}` : `TS-TSS${order.order_number || Date.now()}`;\n    \n    // submissionId: 'TSS9183' (without # or TS- prefix)\n    const submissionId = tssNumber || `TSS${order.order_number || Date.now()}`;\n    \n    // shopifyOrderNumber: the numeric Shopify ID\n    const shopifyOrderNumber = order.id || '';\n\n    // Extract order details with validation\n    const hasRushTag = (order.tags || '').toLowerCase().includes('rush');\n    const has24HourTag = (order.tags || '').toLowerCase().includes('24 hour') || \n                         (order.tags || '').toLowerCase().includes('24hr');\n    const hasSuperRushTag = (order.tags || '').toLowerCase().includes('super rush');\n    \n    // Determine rush service level for Production Option\n    let productionOption = 'Standard 2-3 Days'; // Default\n    let rushService = false; // Checkbox - boolean\n    \n    if (hasSuperRushTag || has24HourTag) {\n      productionOption = 'Super Rush 24 hrs';\n      rushService = true;\n    } else if (hasRushTag) {\n      productionOption = 'Rush 1-2 Days';\n      rushService = true;\n    }\n    \n    const precut = (order.tags || '').toLowerCase().includes('precut') || \n                   (order.tags || '').toLowerCase().includes('pre-cut');\n    \n    // Check for gang sheet required - includes \"by Size\" products\n    const gangSheetRequired = (order.line_items || []).some(li => \n      (li.title || '').toLowerCase().includes('gang sheet') ||\n      (li.title || '').toLowerCase().includes('by size') ||\n      (li.properties || []).some(p => p.name === 'Gang Sheet' && p.value)\n    );\n    \n    const shippingLine = (order.shipping_lines && order.shipping_lines[0]) || {};\n    const shippingAmount = parseFloat(order.total_shipping_price_set?.shop_money?.amount || 0);\n    const needsFile = orderNeedsFiles(order.line_items || []);\n    \n    // Determine facility for this order\n    const facility = determineFacility(order, order.line_items || []);\n    \n    // Extract all product types\n    const productTypes = [...new Set((order.line_items || []).map(li => detectProductType(li)))];\n    \n    // Extract discount information\n    const discountCodes = order.discount_codes || [];\n    const discountAmount = parseFloat(order.total_discounts || 0);\n    \n    // Check if this is a sample pack only order\n    const isSamplePackOnly = isSamplePackOnlyOrder(order.line_items || [], shippingAmount);\n    \n    // Determine fulfillment and shipping options\n    let fulfillmentOption = 'Ship'; // Default\n    let shippingOption = 'Ground'; // Default\n    \n    const shippingTitle = (shippingLine.title || '').toLowerCase();\n    const shippingCode = (shippingLine.code || '').toLowerCase();\n    const shippingText = shippingTitle + ' ' + shippingCode;\n    \n    // First check if it's Will Call (fulfillment option)\n    if (shippingText.includes('will call') || \n        shippingText.includes('pickup') || \n        shippingText.includes('pick up') ||\n        shippingText.includes('local') ||\n        shippingText.includes('transfer superstars hq') ||\n        shippingAmount === 0) {\n      fulfillmentOption = 'Will Call';\n      shippingOption = null; // No shipping option needed for Will Call\n    } else {\n      // It's a Ship order, determine shipping speed\n      if (shippingText.includes('overnight') || \n          shippingText.includes('next day') || \n          shippingText.includes('1 day') ||\n          shippingText.includes('1-day') ||\n          shippingText.includes('priority overnight')) {\n        shippingOption = 'Overnight';\n      } else if (shippingText.includes('express') || \n                 shippingText.includes('2 day') || \n                 shippingText.includes('2-day') ||\n                 shippingText.includes('second day')) {\n        shippingOption = 'Express';\n      } else {\n        shippingOption = 'Ground';\n      }\n    }\n    \n    // Extract order tags - lowercase, meaningful tags\n    const orderTags = [];\n    \n    // Add tags from order.tags\n    if (order.tags) {\n      const rawTags = order.tags.split(',').map(t => t.trim().toLowerCase()).filter(Boolean);\n      \n      // Filter and add meaningful tags\n      rawTags.forEach(tag => {\n        if (tag.includes('rush')) orderTags.push('rush');\n        if (tag.includes('precut') || tag.includes('pre-cut')) orderTags.push('precut');\n        if (tag.includes('sample')) orderTags.push('sample');\n        if (tag.includes('wholesale')) orderTags.push('wholesale');\n        if (tag.includes('repeat')) orderTags.push('repeat-customer');\n        if (tag.includes('vip')) orderTags.push('vip');\n        if (tag.includes('priority')) orderTags.push('priority');\n      });\n    }\n    \n    // Add automatic tags based on order properties\n    if (rushService && !orderTags.includes('rush')) orderTags.push('rush');\n    if (precut && !orderTags.includes('precut')) orderTags.push('precut');\n    if (gangSheetRequired && !orderTags.includes('gang-sheet')) orderTags.push('gang-sheet');\n    if (isSamplePackOnly && !orderTags.includes('sample')) orderTags.push('sample');\n    \n    // Add customer-based tags\n    if (order.customer?.tags?.includes('wholesale') && !orderTags.includes('wholesale')) {\n      orderTags.push('wholesale');\n    }\n    if (order.customer?.orders_count > 1 && !orderTags.includes('repeat-customer')) {\n      orderTags.push('repeat-customer');\n    }\n    if (order.total_price > 500 && !orderTags.includes('high-value')) {\n      orderTags.push('high-value');\n    }\n    \n    // Add payment tags\n    if (order.financial_status === 'paid' && !orderTags.includes('paid')) {\n      orderTags.push('paid');\n    }\n    \n    // Remove duplicates\n    const uniqueTags = [...new Set(orderTags)];\n    \n    // Determine priority level based on production option\n    let priorityLevel = 'Normal';\n    if (rushService) priorityLevel = 'High';\n    \n    // Create order summary\n    const orderSummary = `Order: ${orderId}\nDate: ${new Date(order.created_at).toLocaleDateString()}\nCustomer: ${order.customer?.first_name} ${order.customer?.last_name} (${order.customer?.email || order.email})\n${order.billing_address?.company ? `Company: ${order.billing_address.company}\\n` : ''}\nItems: ${(order.line_items || []).length} item(s)\n${productTypes.length > 0 ? `Products: ${productTypes.join(', ')}\\n` : ''}\nTotal: ${order.total_price} ${order.currency}\n${rushService ? `\u26a1 ${productionOption}\\n` : ''}${precut ? '\u2702\ufe0f Pre-cut Required\\n' : ''}${gangSheetRequired ? '\ud83d\udccf Gang Sheet Required\\n' : ''}\nFulfillment: ${fulfillmentOption}${fulfillmentOption === 'Ship' ? ` - ${shippingOption}` : ''}\n${order.note ? `\\nCustomer Notes: ${order.note}` : ''}\n${discountCodes.length > 0 ? `\\nDiscounts: ${discountCodes.map(d => d.code).join(', ')} (-${discountAmount})` : ''}\nStatus: ${order.financial_status === 'paid' ? '\u2705 Paid' : '\u23f3 Payment Pending'}`;\n    \n    // Determine file status\n    let fileStatus = 'All Files Received';\n    if (needsFile) fileStatus = 'Awaiting Files';\n    else if ((order.line_items || []).some(li => {\n      const props = li.properties || [];\n      return props.some(p => p.name === '_dpi300_image' && !p.value);\n    })) fileStatus = 'Processing';\n\n    const orderCanon = {\n      // UPDATED: Identification with new format\n      orderId,           // 'TS-TSS9183'\n      submissionId,      // 'TSS9183'\n      source: 'Shopify',\n      shopifyOrderNumber, // numeric ID like 6329978978592\n      \n      // Timestamps\n      orderDate: order.created_at || new Date().toISOString(),\n      createdAt: order.created_at || new Date().toISOString(),\n      updatedAt: order.updated_at || new Date().toISOString(),\n      paidAt: order.processed_at || null,\n      fulfilledAt: order.closed_at || null,\n      \n      // Customer data - enhanced\n      customer: {\n        id: (order.customer?.id || '').toString(),\n        email: order.customer?.email || order.email || order.contact_email || '',\n        name: order.customer?.first_name && order.customer?.last_name ? \n              `${order.customer.first_name} ${order.customer.last_name}` :\n              order.billing_address?.name || order.shipping_address?.name || 'Unknown',\n        firstName: order.customer?.first_name || order.billing_address?.first_name || order.shipping_address?.first_name || '',\n        lastName: order.customer?.last_name || order.billing_address?.last_name || order.shipping_address?.last_name || '',\n        phone: order.customer?.phone || order.billing_address?.phone || order.shipping_address?.phone || order.phone || '',\n        company: order.billing_address?.company || order.shipping_address?.company || order.customer?.default_address?.company || '',\n        tags: order.customer?.tags || '',\n        note: order.customer?.note || '',\n        emailOptIn: order.buyer_accepts_marketing || false,\n        smsOptIn: order.customer?.sms_marketing_consent?.state === 'subscribed' || false,\n        taxExempt: order.customer?.tax_exempt || false,\n        verifiedEmail: order.customer?.verified_email || false,\n        ordersCount: order.customer?.orders_count || 1,\n        totalSpent: order.customer?.total_spent || order.total_price || 0\n      },\n      \n      // Shipping address - complete with formatting\n      shipping: {\n        fullAddress: createFullAddress(order.shipping_address),\n        name: order.shipping_address?.name || '',\n        firstName: order.shipping_address?.first_name || '',\n        lastName: order.shipping_address?.last_name || '',\n        company: order.shipping_address?.company || '',\n        address1: order.shipping_address?.address1 || '',\n        address2: order.shipping_address?.address2 || '',\n        city: order.shipping_address?.city || '',\n        state: order.shipping_address?.province_code || '',\n        zip: order.shipping_address?.zip || '',\n        country: order.shipping_address?.country || '',\n        countryCode: order.shipping_address?.country_code || '',\n        phone: order.shipping_address?.phone || '',\n        method: shippingOption  // DEPRECATED - use fulfillmentOption and shippingOption instead\n      },\n      \n      // Billing address - complete with formatting\n      billing: {\n        fullAddress: createFullAddress(order.billing_address),\n        name: order.billing_address?.name || '',\n        firstName: order.billing_address?.first_name || '',\n        lastName: order.billing_address?.last_name || '',\n        company: order.billing_address?.company || '',\n        address1: order.billing_address?.address1 || '',\n        address2: order.billing_address?.address2 || '',\n        city: order.billing_address?.city || '',\n        state: order.billing_address?.province_code || '',\n        zip: order.billing_address?.zip || '',\n        country: order.billing_address?.country || '',\n        countryCode: order.billing_address?.country_code || '',\n        phone: order.billing_address?.phone || ''\n      },\n      \n      // Financial data - enhanced\n      financial: {\n        subtotal: parseFloat(order.subtotal_price || 0),\n        shipping: shippingAmount,\n        tax: parseFloat(order.total_tax || 0),\n        total: parseFloat(order.total_price || 0),\n        discountAmount: discountAmount,\n        discountCodes: discountCodes.map(d => d.code).join(', '),\n        currency: order.currency || 'USD',\n        paymentStatus: order.financial_status === 'paid' ? 'Paid' : 'Pending Payment',\n        paymentMethod: (order.payment_gateway_names && order.payment_gateway_names[0]) || 'Unknown',\n        refundedAmount: parseFloat(order.total_refunded || 0),\n        outstandingBalance: parseFloat(order.total_outstanding || 0)\n      },\n      \n      // Order status and options\n      status: {\n        orderStatus: 'New',\n        fulfillmentStatus: order.fulfillment_status || null,\n        syncStatus: 'Success',\n        qcStatus: 'Not Started'\n      },\n      \n      // Production options with facility\n      options: {\n        rushService,  // Boolean checkbox\n        productionOption,  // \"Standard 2-3 Days\", \"Rush 1-2 Days\", \"Super Rush 24 hrs\"\n        fulfillmentOption,  // \"Ship\" or \"Will Call\"\n        shippingOption,  // \"Ground\", \"Express\", \"Overnight\" (null for Will Call)\n        precut,\n        gangSheetRequired,\n        needsFile,\n        notes: order.note || '',\n        customerNotes: order.note || '',\n        internalNotes: '',\n        tags: uniqueTags.join(','), // lowercase, comma-separated\n        priorityLevel,\n        productTypes: productTypes.join(', '),\n        fileStatus,\n        isSamplePackOnly,\n        facility,\n        orderSummary\n      },\n      \n      // Summary fields\n      summary: {\n        itemCount: (order.line_items || []).length,\n        sourceUrl: `https://admin.shopify.com/store/transfer-superstars/orders/${order.id || ''}`\n      },\n      \n      // Complete metadata\n      meta: {\n        shopify: order,\n        facility,\n        processedAt: new Date().toISOString()\n      }\n    };\n\n    // Create array of line items with complete mapping\n    const lineItems = (order.line_items || []).map(li => {\n      // Extract all properties\n      const properties = li.properties || [];\n      const propertiesObj = {};\n      properties.forEach(p => {\n        if (p.name) propertiesObj[p.name] = p.value;\n      });\n      \n      // File handling\n      const originalImage = properties.find(p => p.name === '_original_image');\n      const dpi300Image = properties.find(p => p.name === '_dpi300_image');\n      const previewImage = properties.find(p => p.name === 'Preview');\n      const printReadyFile = properties.find(p => p.name === '_Print Ready File');\n      \n      // Extract dimensions with multiple fallbacks\n      const sizeProp = properties.find(p => /size/i.test(p.name||''))?.value || '';\n      const dimensionsProp = properties.find(p => p.name === 'dimensions')?.value || '';\n      const dims = sizeProp || dimensionsProp || \n                   (li.variant_title || '').replace(/[^\\d.x]/g, '') ||\n                   ((li.sku || '').match(/(\\d+\\.?\\d*)x(\\d+\\.?\\d*)/)||[]).join('x');\n      \n      // File quality info\n      const dpi = properties.find(p => p.name === 'dpi')?.value || '';\n      const colorMode = properties.find(p => p.name === 'color_mode')?.value || '';\n      const fileFormat = properties.find(p => p.name === 'file_format')?.value || '';\n      \n      // Determine file URL (prioritize DPI300, then print ready, then original)\n      const fileUrl = dpi300Image?.value || printReadyFile?.value || \n                     originalImage?.value || previewImage?.value || '';\n      \n      // Get filename - extract from URL if title is generic\n      let fileName = properties.find(p => p.name === 'File name')?.value || '';\n      \n      // If no filename or title is a default product name, extract from URL\n      if (!fileName || isDefaultProductTitle(li.title)) {\n        if (fileUrl) {\n          fileName = extractFilenameFromUrl(fileUrl);\n        }\n      }\n      \n      // Production options\n      const isPrecut = properties.find(p => p.name === 'Precut')?.value === 'Yes' ||\n                      properties.find(p => p.name === 'Pre-cut')?.value === 'Yes' ||\n                      precut; // Inherit from order level\n      const addWeeding = properties.find(p => p.name === 'Add Weeding')?.value === 'Yes';\n      const isGangSheet = properties.find(p => p.name === 'Gang Sheet')?.value === 'Yes' ||\n                         detectProductType(li) === 'Gang Sheet' ||\n                         detectProductType(li) === 'DTF Gang Sheet' ||\n                         detectProductType(li) === 'UV Gang Sheet';\n      const transferTape = properties.find(p => p.name === 'Transfer Tape')?.value === 'Yes';\n      const gangSheetLength = parseFloat(properties.find(p => p.name === 'Gang Sheet Length')?.value || 0);\n\n      // Check if this is a sample pack\n      const isSamplePack = isSamplePackItem(li);\n\n      // Determine item status\n      let itemStatus = 'Pending';\n      \n      // Sample packs are always ready - they don't need files\n      if (isSamplePack) {\n        itemStatus = 'Ready';\n      } else if (fileUrl && dpi300Image?.value) {\n        itemStatus = 'Ready';\n      } else if (fileUrl) {\n        itemStatus = 'Processing';\n      } else {\n        itemStatus = 'Pending';\n      }\n\n      // Determine artwork QC status\n      let artworkQC = 'Pending';\n      if (properties.find(p => p.name === 'QC Approved')?.value === 'Yes') {\n        artworkQC = 'Approved';\n      } else if (properties.find(p => p.name === 'QC Rejected')?.value === 'Yes') {\n        artworkQC = 'Rejected';\n      }\n\n      return {\n        // UPDATED: Identification with new orderId format\n        itemUid: `${orderId}-${li.id || Date.now()}`,  // 'TS-TSS9183-123456'\n        orderId,  // 'TS-TSS9183'\n        lineItemId: (li.id || Date.now()).toString(),\n        \n        // Product info with proper type detection\n        productType: detectProductType(li),\n        productId: (li.product_id || '').toString(),\n        variantId: (li.variant_id || '').toString(),\n        sku: li.sku || '',\n        title: li.title || '',\n        variantTitle: li.variant_title || '',\n        vendor: li.vendor || '',\n        \n        // Quantities and pricing\n        qty: Number(li.quantity || 1),\n        unitPrice: Number(li.price || 0),\n        compareAtPrice: Number(li.compare_at_price || 0),\n        totalDiscount: Number(li.total_discount || 0),\n        \n        // Physical properties\n        dimensions: dims,\n        weight: li.grams || 0,\n        requiresShipping: li.requires_shipping !== false,\n        \n        // File information - Sample packs don't need files\n        fileUrl: isSamplePack ? 'N/A - Sample Pack' : fileUrl,\n        needsFile: isSamplePack ? false : !fileUrl,\n        fileName: isSamplePack ? 'Sample Pack - No File Required' : fileName,\n        originalFileUrl: isSamplePack ? '' : (originalImage?.value || ''),\n        processedFileUrl: isSamplePack ? '' : (dpi300Image?.value || ''),\n        previewUrl: isSamplePack ? '' : (previewImage?.value || ''),\n        \n        // File quality\n        fileDpi: Number(dpi) || 300,\n        fileColorMode: colorMode || 'RGB',\n        fileFormat: fileFormat || (fileName ? fileName.split('.').pop()?.toUpperCase() : 'PNG') || 'PNG',\n        fileDimensions: dimensionsProp,\n        \n        // Production options\n        isPrecut,\n        addWeeding,\n        isGangSheet,\n        transferTape,\n        gangSheetLength,\n        isSamplePack,\n        \n        // Fulfillment\n        fulfillableQuantity: li.fulfillable_quantity || li.quantity || 0,\n        fulfillmentService: li.fulfillment_service || 'manual',\n        fulfillmentStatus: li.fulfillment_status || null,\n        \n        // Tax info\n        taxable: li.taxable !== false,\n        \n        // Gift card\n        giftCard: li.gift_card || false,\n        \n        // Status\n        itemStatus,\n        artworkQC,\n        qcNotes: properties.find(p => p.name === 'QC Notes')?.value || '',\n        \n        // Facility assignment\n        facility: facility,\n        \n        // Complete metadata\n        meta: {\n          shopify: {\n            lineItemId: li.id,\n            properties: properties,\n            propertiesObject: propertiesObj,\n            productHandle: li.product_handle || ''\n          },\n          facility: facility,\n          processedAt: new Date().toISOString()\n        }\n      };\n    });\n\n    // Add this order with its items to output\n    allOutputs.push({\n      json: {\n        order: orderCanon,\n        items: lineItems\n      }\n    });\n  } catch (error) {\n    // Log error but continue processing other orders\n    console.error('Error processing order:', error.message);\n  }\n});\n\nreturn allOutputs.length > 0 ? allOutputs : [{ json: { error: 'No valid orders to process' } }];"
      },
      "id": "936e332c-de2d-4180-abef-f7172a0ebaca",
      "name": "Function - Parse Shopify",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        -60,
        -300
      ],
      "onError": "continueRegularOutput"
    },
    {
      "parameters": {
        "jsCode": "// Helper function to extract filename from URL\nfunction extractFilenameFromUrl(url) {\n  if (!url) return '';\n  \n  try {\n    // Decode the URL first to handle encoded characters\n    const decodedUrl = decodeURIComponent(url);\n    // Extract the last part of the URL path\n    const urlParts = decodedUrl.split('/');\n    const filename = urlParts[urlParts.length - 1];\n    \n    // Remove query parameters if present\n    return filename.split('?')[0] || '';\n  } catch (e) {\n    // If decoding fails, try without decoding\n    const urlParts = url.split('/');\n    const filename = urlParts[urlParts.length - 1];\n    return filename.split('?')[0] || '';\n  }\n}\n\n// Enhanced product type detection based on Airtable schema and form data\nfunction detectProductType(productType, formName, answers, formId) {\n  const type = (productType || '').toLowerCase();\n  const form = (formName || '').toLowerCase();\n  \n  // First check direct product type answer\n  if (productType) {\n    const typeMap = {\n      'dtf': 'DTF Transfers',\n      'dtf transfer': 'DTF Transfers',\n      'dtf transfers': 'DTF Transfers',\n      'dtf gang sheet': 'DTF Gang Sheet',\n      'uv gang sheet': 'UV Gang Sheet',\n      'gang sheet': 'Gang Sheet',\n      'gang sheets': 'Gang Sheet',\n      'uv': 'UV Stickers',\n      'uv sticker': 'UV Stickers',\n      'uv stickers': 'UV Stickers',\n      'sublimation': 'Sublimation',\n      'heat press': 'Heat Press',\n      'heat tape': 'Heat Tape',\n      'matt finishing': 'Matt Finishing Sheet',\n      'matt finishing sheet': 'Matt Finishing Sheet',\n      'laser alignment': 'Laser Alignment',\n      'alignment tool': 'Alignment Tool',\n      'accessories': 'Accessories',\n      'dtf + uv': 'DTF + UV DTF',\n      'dtf and uv': 'DTF + UV DTF',\n      'uv dtf': 'DTF + UV DTF'\n    };\n    \n    for (const [key, value] of Object.entries(typeMap)) {\n      if (type === key || type.includes(key)) {\n        // Special handling for generic \"Gang Sheet\"\n        if (value === 'Gang Sheet') {\n          // Determine based on form\n          if (form.includes('uv') || formId === '233115151476147') {\n            return 'UV Gang Sheet';\n          } else {\n            return 'DTF Gang Sheet';\n          }\n        }\n        return value;\n      }\n    }\n  }\n  \n  // Check form name for product type hints\n  if (form.includes('uv') && form.includes('dtf')) return 'DTF + UV DTF';\n  if (form.includes('uv') && form.includes('gang')) return 'UV Gang Sheet';\n  if (form.includes('dtf') && form.includes('gang')) return 'DTF Gang Sheet';\n  if (form.includes('uv sticker') || form.includes('uv-sticker')) return 'UV Stickers';\n  if (form.includes('uv')) return 'UV Stickers';\n  if (form.includes('sublimation')) return 'Sublimation';\n  if (form.includes('heat press')) return 'Heat Press';\n  if (form.includes('gang sheet') || form.includes('gangsheet')) {\n    // Try to determine if UV or DTF\n    if (form.includes('uv') || formId === '233115151476147') {\n      return 'UV Gang Sheet';\n    }\n    return 'DTF Gang Sheet'; // Default to DTF\n  }\n  \n  // Check special instructions or notes for product type hints\n  if (answers) {\n    for (const answer of Object.values(answers)) {\n      const text = (answer.answer || answer.prettyFormat || '').toString().toLowerCase();\n      if (text.includes('uv') && text.includes('dtf')) return 'DTF + UV DTF';\n      if (text.includes('uv') && text.includes('gang')) return 'UV Gang Sheet';\n      if (text.includes('dtf') && text.includes('gang')) return 'DTF Gang Sheet';\n      if (text.includes('uv sticker')) return 'UV Stickers';\n      if (text.includes('gang sheet')) {\n        if (text.includes('uv') || formId === '233115151476147') {\n          return 'UV Gang Sheet';\n        }\n        return 'DTF Gang Sheet';\n      }\n      if (text.includes('sublimation')) return 'Sublimation';\n      if (text.includes('alignment tool')) return 'Alignment Tool';\n    }\n  }\n  \n  // Default to DTF Transfers\n  return 'DTF Transfers';\n}\n\n// Determine facility based on form data and shipping location\nfunction determineFacility(formName, shippingState, productType) {\n  // For JotForm orders, leave facility blank for user selection\n  return null;\n}\n\n// Extract order tags based on form data\nfunction extractOrderTags(rushService, precut, formName, answers) {\n  const tags = [];\n  \n  if (rushService) tags.push('rush');\n  if (precut) tags.push('precut');\n  \n  // Add form-specific tags\n  const form = (formName || '').toLowerCase();\n  if (form.includes('wholesale') || form.includes('b2b')) {\n    tags.push('wholesale');\n  }\n  \n  if (form.includes('sample')) {\n    tags.push('sample');\n  }\n  \n  // Check answers for additional tags\n  if (answers) {\n    for (const [key, answer] of Object.entries(answers)) {\n      const text = (answer.text || '').toLowerCase();\n      const value = (answer.answer || answer.prettyFormat || '').toString().toLowerCase();\n      \n      if (text.includes('repeat customer') && value.includes('yes')) {\n        tags.push('repeat-customer');\n      }\n      \n      if (text.includes('referral') && value) {\n        tags.push('referral');\n      }\n    }\n  }\n  \n  return tags;\n}\n\n// Process ALL items\nconst items = $input.all();\n\nreturn items.map(item => {\n  try {\n    const submission = item.json.payload || item.json;\n    const answers = submission.answers || {};\n    \n    // Validate submission\n    if (!submission.id) {\n      throw new Error('Invalid JotForm submission - no ID');\n    }\n    \n    // Get form metadata from the tagged data\n    const formName = item.json.form_name || '';\n    const formLayout = item.json.form_layout || '';\n    const formId = submission.form_id || '';\n    \n    // Determine prefix based on form type\n    // Check form ID, form name, and form layout for UV forms\n    const isUVForm = formId === '233115151476147' || \n                     formName.toLowerCase().includes('uv') || \n                     formLayout.toLowerCase().includes('uv');\n    const prefix = isUVForm ? 'UV' : 'DTF';\n    \n    // UPDATED: Format IDs according to new requirements\n    // JotForm: orderId = \"DTF-2398234792374\" or \"UV-234792873472\", submissionId = \"2398234792374\"\n    const submissionId = submission.id.toString();\n    const orderId = `${prefix}-${submissionId}`;\n\n    let customer = {\n      email: '',\n      name: '',\n      firstName: '',\n      lastName: '',\n      phone: '',\n      company: '',\n      emailOptIn: true,\n      smsOptIn: false,\n      taxExempt: false,\n      verifiedEmail: false,\n      tags: '',\n      note: ''\n    };\n\n    let shipping = {\n      fullAddress: '',\n      name: '',\n      firstName: '',\n      lastName: '',\n      company: '',\n      address1: '',\n      address2: '',\n      city: '',\n      state: '',\n      zip: '',\n      country: 'US',\n      countryCode: 'US',\n      phone: '',\n      method: 'Ground' // Default to Ground\n    };\n    \n    let billing = {\n      fullAddress: '',\n      name: '',\n      firstName: '',\n      lastName: '',\n      company: '',\n      address1: '',\n      address2: '',\n      city: '',\n      state: '',\n      zip: '',\n      country: 'US',\n      countryCode: 'US',\n      phone: ''\n    };\n\n    let orderDetails = {\n      productType: '',\n      quantity: 1,\n      dimensions: '',\n      fileData: [], // Changed to store file objects with url and name\n      specialInstructions: '',\n      productionOption: 'Standard 2-3 Days', // Default production option\n      rushService: false, // Boolean checkbox\n      precut: false,\n      gangSheetRequired: false,\n      addWeeding: false,\n      transferTape: false,\n      paymentMethod: 'Pending',\n      referralSource: '',\n      fulfillmentOption: 'Ship', // Default fulfillment option\n      shippingOption: 'Ground' // Default shipping option\n    };\n\n    // Debug log to see what we're getting\n    console.log(`Processing submission ${submissionId} with ${Object.keys(answers).length} answers`);\n\n    // Parse JotForm answers - use for...of instead of forEach\n    for (const [key, answer] of Object.entries(answers)) {\n      if (!answer || typeof answer !== 'object') continue;\n      \n      const text = answer.text || '';\n      const value = answer.answer || answer.prettyFormat || '';\n      \n      // Debug file upload fields\n      if (answer.type === 'control_fileupload' || text.includes('Upload') || text.includes('File')) {\n        console.log(`Found file upload field ${key}:`, answer);\n      }\n      \n      // Customer info - improved detection with specific field IDs\n      // Email - check specific field ID 331 first\n      if (key === '331') {\n        // This is the email field\n        if (typeof answer.answer === 'string') {\n          customer.email = answer.answer;\n        } else if (typeof answer.prettyFormat === 'string') {\n          customer.email = answer.prettyFormat;\n        } else if (typeof value === 'string') {\n          customer.email = value;\n        }\n        console.log(`Found email in field 331: ${customer.email}`);\n      } else if (answer.type === 'control_email' || \n                 text.toLowerCase().includes('email') || \n                 text.toLowerCase().includes('e-mail')) {\n        // Fallback email detection\n        if (typeof value === 'string' && value.includes('@')) {\n          customer.email = value;\n        } else if (typeof answer.answer === 'string' && answer.answer.includes('@')) {\n          customer.email = answer.answer;\n        } else if (answer.prettyFormat && typeof answer.prettyFormat === 'string') {\n          customer.email = answer.prettyFormat;\n        }\n      } else if (answer.type === 'control_fullname' || \n                 (text.toLowerCase().includes('name') && \n                  !text.toLowerCase().includes('company') && \n                  !text.toLowerCase().includes('business'))) {\n        // Handle fullname field - JotForm often returns an object\n        if (typeof answer.answer === 'object' && answer.answer) {\n          customer.firstName = answer.answer.first || '';\n          customer.lastName = answer.answer.last || '';\n          customer.name = `${customer.firstName} ${customer.lastName}`.trim();\n        } else if (typeof value === 'string' && value) {\n          customer.name = value;\n          const nameParts = value.split(' ');\n          customer.firstName = nameParts[0] || '';\n          customer.lastName = nameParts.slice(1).join(' ') || '';\n        }\n      } else if (answer.type === 'control_phone' || text.toLowerCase().includes('phone')) {\n        customer.phone = answer.answer?.full || (typeof value === 'string' ? value : '');\n      } else if ((text.toLowerCase().includes('company') || text.toLowerCase().includes('business')) && \n                 !text.toLowerCase().includes('address')) {\n        // Only capture as company if it's actually a company field, not a date or other field\n        const companyValue = typeof value === 'string' ? value : '';\n        // Check if the value looks like a date (e.g., \"Wed Jun 25\")\n        if (!companyValue.match(/^(Mon|Tue|Wed|Thu|Fri|Sat|Sun)\\s+(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\\s+\\d+/i)) {\n          customer.company = companyValue;\n        }\n      }\n      \n      // Address info\n      if ((answer.type === 'control_address' || text.toLowerCase().includes('address')) && answer.answer && typeof answer.answer === 'object') {\n        const addr = answer.answer;\n        shipping.address1 = addr.addr_line1 || '';\n        shipping.address2 = addr.addr_line2 || '';\n        shipping.city = addr.city || '';\n        shipping.state = addr.state || '';\n        shipping.zip = addr.postal || '';\n        shipping.country = addr.country || 'United States';\n        shipping.countryCode = addr.country === 'United States' ? 'US' : addr.country?.substring(0, 2).toUpperCase() || 'US';\n        \n        // Format full address\n        const parts = [shipping.address1, shipping.address2, shipping.city, shipping.state, shipping.zip].filter(Boolean);\n        shipping.fullAddress = parts.join(', ');\n        \n        // Copy to billing\n        billing = {...shipping};\n      }\n      \n      // Product details - Enhanced detection\n      if (text.includes('Product Type') || text.includes('What are you printing') || text.includes('Service Type')) {\n        // Handle multiple choice or dropdown answers\n        if (typeof value === 'string') {\n          orderDetails.productType = value;\n        } else if (Array.isArray(value) && value.length > 0) {\n          orderDetails.productType = value[0];\n        }\n      } else if (text.includes('Quantity') || text.includes('How many')) {\n        // Handle matrix field for quantity\n        if (answer.answer && Array.isArray(answer.answer)) {\n          // Matrix field structure: [[row_name, col1_value, col2_value, ...]]\n          if (Array.isArray(answer.answer[0])) {\n            orderDetails.quantity = parseInt(answer.answer[0][2]) || parseInt(answer.answer[0][1]) || 1;\n          }\n        } else if (typeof value === 'string' || typeof value === 'number') {\n          orderDetails.quantity = parseInt(value) || 1;\n        }\n      } else if (text.includes('Size') || text.includes('Dimensions')) {\n        if (typeof value === 'string') {\n          orderDetails.dimensions = value;\n        } else if (answer.answer && typeof answer.answer === 'object') {\n          // Handle structured dimension answers\n          const width = answer.answer.width || '';\n          const height = answer.answer.height || '';\n          if (width && height) {\n            orderDetails.dimensions = `${width}x${height}`;\n          }\n        }\n      } else if (text.includes('Special Instructions') || text.includes('Notes') || text.includes('Additional')) {\n        orderDetails.specialInstructions = typeof value === 'string' ? value : '';\n      } else if (text.includes('Rush') || text.includes('Expedited') || text.includes('24 hour') || text.includes('Production')) {\n        const rushValue = typeof value === 'string' ? value : '';\n        if (rushValue.toLowerCase().includes('super') || rushValue.toLowerCase().includes('24')) {\n          orderDetails.productionOption = 'Super Rush 24 hrs';\n          orderDetails.rushService = true;\n        } else if (rushValue.toLowerCase().includes('yes') || rushValue.toLowerCase().includes('rush') || rushValue.toLowerCase().includes('1-2')) {\n          orderDetails.productionOption = 'Rush 1-2 Days';\n          orderDetails.rushService = true;\n        } else {\n          orderDetails.productionOption = 'Standard 2-3 Days';\n          orderDetails.rushService = false;\n        }\n      } else if (text.includes('Pre-cut') || text.includes('Precut')) {\n        const precutValue = typeof value === 'string' ? value : '';\n        orderDetails.precut = precutValue.toLowerCase().includes('yes');\n      } else if (text.includes('Gang Sheet')) {\n        const gangValue = typeof value === 'string' ? value : '';\n        orderDetails.gangSheetRequired = gangValue.toLowerCase().includes('yes');\n      } else if (text.includes('Weeding')) {\n        const weedingValue = typeof value === 'string' ? value : '';\n        orderDetails.addWeeding = weedingValue.toLowerCase().includes('yes');\n      } else if (text.includes('Transfer Tape') || text.includes('Application Tape')) {\n        const tapeValue = typeof value === 'string' ? value : '';\n        orderDetails.transferTape = tapeValue.toLowerCase().includes('yes');\n      } else if (text.includes('Shipping Method') || text.includes('Shipping Option') || text.includes('Delivery Method') || text.includes('Fulfillment')) {\n        const shipValue = typeof value === 'string' ? value : '';\n        // Map to allowed values with more comprehensive detection\n        const shipLower = shipValue.toLowerCase();\n        \n        // First check if it's a Will Call order\n        if (shipLower.includes('will call') || \n            shipLower.includes('pickup') || \n            shipLower.includes('pick up') ||\n            shipLower.includes('local') ||\n            shipLower.includes('in store') ||\n            shipLower.includes('in-store')) {\n          orderDetails.fulfillmentOption = 'Will Call';\n          orderDetails.shippingOption = null; // No shipping needed\n        } else {\n          // It's a Ship order, determine speed\n          orderDetails.fulfillmentOption = 'Ship';\n          \n          if (shipLower.includes('overnight') || \n              shipLower.includes('next day') || \n              shipLower.includes('next-day') ||\n              shipLower.includes('1 day') ||\n              shipLower.includes('1-day') ||\n              shipLower.includes('priority overnight')) {\n            orderDetails.shippingOption = 'Overnight';\n          } else if (shipLower.includes('express') || \n                     shipLower.includes('2 day') || \n                     shipLower.includes('2-day') ||\n                     shipLower.includes('second day') ||\n                     shipLower.includes('expedited')) {\n            orderDetails.shippingOption = 'Express';\n          } else {\n            orderDetails.shippingOption = 'Ground';\n          }\n        }\n      } else if (text.includes('Payment') || text.includes('How will you pay')) {\n        orderDetails.paymentMethod = typeof value === 'string' ? value : 'Pending';\n      } else if (text.includes('How did you hear') || text.includes('Referral')) {\n        orderDetails.referralSource = typeof value === 'string' ? value : '';\n      } else if (text.includes('Marketing') || text.includes('Newsletter')) {\n        const marketingValue = typeof value === 'string' ? value : '';\n        customer.emailOptIn = marketingValue.toLowerCase().includes('yes');\n      } else if (text.includes('SMS') || text.includes('Text')) {\n        const smsValue = typeof value === 'string' ? value : '';\n        customer.smsOptIn = smsValue.toLowerCase().includes('yes');\n      } else if (text.includes('Tax Exempt')) {\n        const taxValue = typeof value === 'string' ? value : '';\n        customer.taxExempt = taxValue.toLowerCase().includes('yes');\n      }\n      \n      // File uploads - Updated to extract filenames\n      if ((answer.type === 'control_fileupload' || text.includes('Upload') || text.includes('File')) && answer.answer) {\n        const files = Array.isArray(answer.answer) ? answer.answer : [answer.answer];\n        files.forEach(fileUrl => {\n          if (fileUrl && typeof fileUrl === 'string') {\n            const fileName = extractFilenameFromUrl(fileUrl);\n            console.log(`Adding file: ${fileName} from URL: ${fileUrl}`);\n            orderDetails.fileData.push({\n              url: fileUrl,\n              name: fileName\n            });\n          }\n        });\n      }\n    }\n\n    // After parsing, ensure shipping has customer info\n    if (customer.name && !shipping.name) {\n      shipping.name = customer.name;\n      shipping.firstName = customer.firstName;\n      shipping.lastName = customer.lastName;\n    }\n    if (customer.company) {\n      shipping.company = customer.company;\n    }\n    if (customer.phone && !shipping.phone) {\n      shipping.phone = customer.phone;\n    }\n\n    // Update billing to match shipping\n    billing = {...shipping};\n\n    console.log(`Found ${orderDetails.fileData.length} files for order ${orderId}`);\n    console.log(`Customer data: name=\"${customer.name}\", email=\"${customer.email}\", phone=\"${customer.phone}\"`);\n\n    // Detect product type with all available data\n    const detectedProductType = detectProductType(orderDetails.productType, formName, answers, formId);\n    \n    // Determine facility\n    const facility = determineFacility(formName, shipping.state, detectedProductType);\n    \n    // Update shipping method to shipping/fulfillment options\n    shipping.method = orderDetails.shippingOption;  // DEPRECATED - use fulfillmentOption and shippingOption instead\n    \n    // Extract order tags\n    const orderTags = [];\n    \n    if (orderDetails.rushService) orderTags.push('rush');\n    if (orderDetails.precut) orderTags.push('precut');\n    if (orderDetails.gangSheetRequired || detectedProductType.includes('Gang Sheet')) orderTags.push('gang-sheet');\n    \n    // Add form-specific tags\n    const form = (formName || '').toLowerCase();\n    if (form.includes('wholesale') || form.includes('b2b')) orderTags.push('wholesale');\n    if (form.includes('sample')) orderTags.push('sample');\n    if (form.includes('custom')) orderTags.push('custom');\n    if (form.includes('bulk')) orderTags.push('bulk');\n    \n    // Add referral tag if applicable\n    if (orderDetails.referralSource) {\n      const referral = orderDetails.referralSource.toLowerCase();\n      if (referral.includes('google')) orderTags.push('google-referral');\n      else if (referral.includes('facebook') || referral.includes('instagram')) orderTags.push('social-referral');\n      else if (referral.includes('friend') || referral.includes('word')) orderTags.push('word-of-mouth');\n      else if (referral.includes('return') || referral.includes('repeat')) orderTags.push('repeat-customer');\n    }\n    \n    // Check for specific product tags\n    if (detectedProductType === 'UV Stickers' || detectedProductType === 'UV Gang Sheet') orderTags.push('uv');\n    if (detectedProductType === 'DTF + UV DTF') orderTags.push('uv', 'dtf');\n    \n    // Determine priority level based on rush service\n    let priorityLevel = 'Normal';\n    if (orderDetails.rushService) priorityLevel = 'High';\n    \n    // Create order summary\n    const orderSummary = `Order: ${orderId}\nDate: ${new Date(submission.created_at).toLocaleDateString()}\nForm: ${formName}\nCustomer: ${customer.name} (${customer.email})\n${customer.company ? `Company: ${customer.company}\\n` : ''}\nProduct: ${detectedProductType}\nQuantity: ${orderDetails.quantity}\n${orderDetails.dimensions ? `Size: ${orderDetails.dimensions}\\n` : ''}\n${orderDetails.rushService ? `\u26a1 ${orderDetails.productionOption}\\n` : ''}${orderDetails.precut ? '\u2702\ufe0f Pre-cut Required\\n' : ''}${orderDetails.gangSheetRequired ? '\ud83d\udccf Gang Sheet Required\\n' : ''}\nFiles: ${orderDetails.fileData.length} uploaded\nFulfillment: ${orderDetails.fulfillmentOption}${orderDetails.fulfillmentOption === 'Ship' ? ` - ${orderDetails.shippingOption}` : ''}\n${orderDetails.specialInstructions ? `\\nInstructions: ${orderDetails.specialInstructions}` : ''}\nPayment: ${orderDetails.paymentMethod}`;\n    \n    // Determine file status\n    let fileStatus = 'Awaiting Files';\n    if (orderDetails.fileData.length > 0) {\n      fileStatus = orderDetails.fileData.length >= orderDetails.quantity ? 'All Files Received' : 'Partial Files Received';\n    }\n    \n    // Determine payment status based on payment method\n    let paymentStatus = 'Pending Payment';\n    if (orderDetails.paymentMethod.toLowerCase().includes('paid') || \n        orderDetails.paymentMethod.toLowerCase().includes('credit card') ||\n        orderDetails.paymentMethod.toLowerCase().includes('paypal')) {\n      paymentStatus = 'Paid';\n    }\n\n    const orderCanon = {\n      // UPDATED: Identification with new format\n      orderId,           // 'DTF-2398234792374' or 'UV-234792873472'\n      submissionId,      // '2398234792374'\n      source: 'JotForm',\n      jotformSubmissionId: submissionId,\n      \n      // Timestamps\n      orderDate: submission.created_at || new Date().toISOString(),\n      createdAt: submission.created_at || new Date().toISOString(),\n      updatedAt: submission.updated_at || submission.created_at || new Date().toISOString(),\n      paidAt: paymentStatus === 'Paid' ? submission.created_at : null,\n      fulfilledAt: null,\n      \n      // Customer data\n      customer: {\n        ...customer,\n        id: '',\n        tags: customer.company ? 'b2b' : 'b2c',\n        ordersCount: 1,\n        totalSpent: 0\n      },\n      \n      // Addresses\n      shipping,\n      billing,\n      \n      // Financial data\n      financial: {\n        subtotal: 0,\n        shipping: 0,\n        tax: 0,\n        total: 0,\n        discountAmount: 0,\n        discountCodes: '',\n        currency: 'USD',\n        paymentStatus,\n        paymentMethod: orderDetails.paymentMethod,\n        refundedAmount: 0,\n        outstandingBalance: 0\n      },\n      \n      // Status\n      status: {\n        orderStatus: 'New',\n        fulfillmentStatus: null,\n        syncStatus: 'Success',\n        qcStatus: 'Not Started'\n      },\n      \n      // Options\n      options: {\n        rushService: orderDetails.rushService,  // Boolean checkbox\n        productionOption: orderDetails.productionOption,  // \"Standard 2-3 Days\", \"Rush 1-2 Days\", \"Super Rush 24 hrs\"\n        fulfillmentOption: orderDetails.fulfillmentOption,  // \"Ship\" or \"Will Call\"\n        shippingOption: orderDetails.shippingOption,  // \"Ground\", \"Express\", \"Overnight\" (null for Will Call)\n        precut: orderDetails.precut,\n        gangSheetRequired: orderDetails.gangSheetRequired || detectedProductType.includes('Gang Sheet'),\n        needsFile: orderDetails.fileData.length === 0,\n        notes: orderDetails.specialInstructions,\n        customerNotes: orderDetails.specialInstructions,\n        internalNotes: '',\n        tags: orderTags.join(','), // lowercase, comma-separated\n        priorityLevel,\n        productTypes: detectedProductType,\n        fileStatus,\n        isSamplePackOnly: false,\n        facility,\n        referralSource: orderDetails.referralSource,\n        orderSummary\n      },\n      \n      // Summary\n      summary: {\n        itemCount: orderDetails.fileData.length || 1,\n        sourceUrl: `https://www.jotform.com/submission/${submissionId}`\n      },\n      \n      // Metadata\n      meta: {\n        jotform: {\n          submissionRaw: submission,\n          formName: formName,\n          formLayout: formLayout,\n          formId: formId,\n          ip: submission.ip || '',\n          userAgent: submission.user_agent || ''\n        },\n        facility,\n        processedAt: new Date().toISOString()\n      }\n    };\n\n    // Create items - one for each uploaded file, or one default item if no files\n    let orderItems = [];\n    \n    if (orderDetails.fileData.length > 0) {\n      // Create an item for each uploaded file\n      orderItems = orderDetails.fileData.map((file, index) => {\n        // Extract file format from filename\n        const fileFormat = file.name.split('.').pop()?.toUpperCase() || 'PNG';\n        \n        // Determine item status\n        const itemStatus = 'Ready';\n        const artworkQC = 'Pending';\n        \n        return {\n          // UPDATED: Identification with new orderId format\n          itemUid: `${orderId}-${index + 1}`,  // 'DTF-2398234792374-1'\n          orderId,  // 'DTF-2398234792374'\n          lineItemId: (index + 1).toString(),\n          \n          // Product info\n          productType: detectedProductType,\n          productId: '',\n          variantId: '',\n          sku: `${prefix}-${submissionId}-${index + 1}`,\n          title: file.name || `${detectedProductType} - Custom`,\n          variantTitle: orderDetails.dimensions || 'Custom Size',\n          vendor: 'Transfer Superstars',\n          \n          // Quantities and pricing\n          qty: orderDetails.quantity,\n          unitPrice: 0,\n          compareAtPrice: 0,\n          totalDiscount: 0,\n          \n          // Physical properties\n          dimensions: orderDetails.dimensions,\n          weight: 0,\n          requiresShipping: orderDetails.fulfillmentOption === 'Ship',\n          \n          // File information\n          fileUrl: file.url,\n          needsFile: false,\n          fileName: file.name,\n          originalFileUrl: file.url,\n          processedFileUrl: '',\n          previewUrl: '',\n          \n          // File quality\n          fileDpi: 300,\n          fileColorMode: 'RGB',\n          fileFormat,\n          fileDimensions: '',\n          \n          // Production options\n          isPrecut: orderDetails.precut,\n          addWeeding: orderDetails.addWeeding,\n          isGangSheet: orderDetails.gangSheetRequired || detectedProductType.includes('Gang Sheet'),\n          transferTape: orderDetails.transferTape,\n          gangSheetLength: 0,\n          isSamplePack: false,\n          \n          // Fulfillment\n          fulfillableQuantity: orderDetails.quantity,\n          fulfillmentService: 'manual',\n          fulfillmentStatus: null,\n          \n          // Tax and other flags\n          taxable: !customer.taxExempt,\n          giftCard: false,\n          \n          // Status\n          itemStatus,\n          artworkQC,\n          qcNotes: '',\n          \n          // Facility\n          facility,\n          \n          // Metadata\n          meta: {\n            jotform: {\n              formId: formId,\n              formName: formName,\n              allFileUrls: orderDetails.fileData,\n              specialInstructions: orderDetails.specialInstructions,\n              fileIndex: index\n            },\n            facility,\n            processedAt: new Date().toISOString()\n          }\n        };\n      });\n    } else {\n      // Create a single item if no files uploaded\n      orderItems = [{\n        // UPDATED: Identification with new orderId format\n        itemUid: `${orderId}-1`,  // 'DTF-2398234792374-1'\n        orderId,  // 'DTF-2398234792374'\n        lineItemId: '1',\n        \n        // Product info\n        productType: detectedProductType,\n        productId: '',\n        variantId: '',\n        sku: `${prefix}-${submissionId}-1`,\n        title: `${detectedProductType} - Custom`,\n        variantTitle: orderDetails.dimensions || 'Custom Size',\n        vendor: 'Transfer Superstars',\n        \n        // Quantities and pricing\n        qty: orderDetails.quantity,\n        unitPrice: 0,\n        compareAtPrice: 0,\n        totalDiscount: 0,\n        \n        // Physical properties\n        dimensions: orderDetails.dimensions,\n        weight: 0,\n        requiresShipping: orderDetails.fulfillmentOption === 'Ship',\n        \n        // File information\n        fileUrl: '',\n        needsFile: true,\n        fileName: '',\n        originalFileUrl: '',\n        processedFileUrl: '',\n        previewUrl: '',\n        \n        // File quality\n        fileDpi: 300,\n        fileColorMode: 'RGB',\n        fileFormat: '',\n        fileDimensions: '',\n        \n        // Production options\n        isPrecut: orderDetails.precut,\n        addWeeding: orderDetails.addWeeding,\n        isGangSheet: orderDetails.gangSheetRequired || detectedProductType.includes('Gang Sheet'),\n        transferTape: orderDetails.transferTape,\n        gangSheetLength: 0,\n        isSamplePack: false,\n        \n        // Fulfillment\n        fulfillableQuantity: orderDetails.quantity,\n        fulfillmentService: 'manual',\n        fulfillmentStatus: null,\n        \n        // Tax and other flags\n        taxable: !customer.taxExempt,\n        giftCard: false,\n        \n        // Status\n        itemStatus: 'Pending Art',\n        artworkQC: 'Pending',\n        qcNotes: '',\n        \n        // Facility\n        facility,\n        \n        // Metadata\n        meta: {\n          jotform: {\n            formId: formId,\n            formName: formName,\n            allFileUrls: [],\n            specialInstructions: orderDetails.specialInstructions\n          },\n          facility,\n          processedAt: new Date().toISOString()\n        }\n      }];\n    }\n\n    return { json: { order: orderCanon, items: orderItems } };\n  } catch (error) {\n    console.error('Error processing JotForm submission:', error.message);\n    return { json: { error: error.message } };\n  }\n});"
      },
      "id": "9aed6ec7-3752-441c-a4ef-a1645022751e",
      "name": "Function - Parse JotForm",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        -60,
        -120
      ],
      "onError": "continueRegularOutput"
    },
    {
      "parameters": {
        "jsCode": "// Parse Jiffy Order with Attachment Storage\n// This is the enhanced version that properly structures attachment data\n\n// Helper function to extract actual filename from URL\nfunction extractFilenameFromUrl(url) {\n  if (!url) return '';\n  // Handle Jiffy URLs with filename parameter\n  const filenameMatch = url.match(/filename=([^&]+)/);\n  if (filenameMatch) {\n    return decodeURIComponent(filenameMatch[1]);\n  }\n  // Fallback to last part of URL\n  const urlParts = url.split('/');\n  const filename = urlParts[urlParts.length - 1];\n  return filename.split('?')[0];\n}\n\n// Extract dimensions and return width, height, and formatted string\nfunction extractDimensionsFromFilename(filename) {\n  if (!filename) return { width: 0, height: 0, dimensions: '' };\n  // Match patterns like \"22.4x48.47in\" or \"22.0x5.95in\"\n  const match = filename.match(/(\\d+(?:\\.\\d+)?)\\s*x\\s*(\\d+(?:\\.\\d+)?)/i);\n  if (match) {\n    const width = parseFloat(match[1]);\n    const height = parseFloat(match[2]);\n    return {\n      width: width,\n      height: height,\n      dimensions: `${width}x${height}`\n    };\n  }\n  return { width: 0, height: 0, dimensions: '' };\n}\n\n// Detect product type from filename\nfunction detectProductTypeFromFilename(filename) {\n  const filenameLower = filename.toLowerCase();\n  if (filenameLower.includes('sublimation')) {\n    return 'Sublimation Gang Sheet';\n  } else if (filenameLower.includes('uv')) {\n    return 'UV Gang Sheet';\n  } else if (filenameLower.includes('dtf') || filenameLower.includes('transfers')) {\n    return 'DTF Gang Sheet';\n  }\n  return 'Gang Sheet'; // Default\n}\n\n// Generate proper title from filename\nfunction generateTitleFromFilename(filename, productType) {\n  const dims = extractDimensionsFromFilename(filename);\n  if (dims.dimensions) {\n    return `${productType} ${dims.dimensions}`;\n  }\n  // Fallback to cleaned filename\n  return filename.replace(/\\.[^/.]+$/, '').replace(/-/g, ' '); // Remove extension and replace dashes\n}\n\n// Helper function to parse formatted text for additional data\nfunction parseFormattedText(text) {\n  const data = {\n    orderType: '',\n    precutQuantity: 0,\n    totalPrintLength: ''\n  };\n  \n  // Extract order type\n  const orderTypeMatch = text.match(/ORDER TYPE:\\s*(.+?)(?:\\n|$)/i);\n  if (orderTypeMatch) {\n    data.orderType = orderTypeMatch[1].trim();\n  }\n  \n  // Extract precut quantity\n  const precutMatch = text.match(/Pre-cut Quantity:\\s*(\\d+)/i);\n  if (precutMatch) {\n    data.precutQuantity = parseInt(precutMatch[1]);\n  }\n  \n  // Extract total print length\n  const lengthMatch = text.match(/Total Print Length:\\s*([\\d.]+)\\s*inches/i);\n  if (lengthMatch) {\n    data.totalPrintLength = lengthMatch[1];\n  }\n  \n  return data;\n}\n\nreturn items.map(item => {\n  try {\n    // Extract the payload data\n    const jiffyData = item.json.payload || item.json;\n    \n    // Validate Jiffy data\n    if (!jiffyData.poNumber && !jiffyData.orderId) {\n      throw new Error('Invalid Jiffy order - no PO number or order ID');\n    }\n    \n    // Extract key identifiers\n    const poNumber = jiffyData.poNumber || jiffyData.jiffyPoNumber || '';\n    const orderId = jiffyData.orderId || `JIFFY-${poNumber}`;\n    const submissionId = poNumber;\n    \n    // Parse additional data from HTML/formatted text\n    const parsedData = parseFormattedText(jiffyData.html || jiffyData.formatted_text || '');\n    \n    // Determine order type and product types\n    let orderType = jiffyData.orderType || parsedData.orderType || 'Unknown';\n    let productTypes = [];\n    let gangSheetRequired = false;\n    let precut = false;\n    \n    // Analyze order type and files to determine product types\n    const orderTypeLower = orderType.toLowerCase();\n    const hasGangSheetUrls = jiffyData.gangSheetUrls && jiffyData.gangSheetUrls.length > 0;\n    \n    if (orderTypeLower.includes('uv') && (orderTypeLower.includes('dtf') || hasGangSheetUrls)) {\n      productTypes.push('UV Gang Sheet');\n      gangSheetRequired = true;\n    } else if (orderTypeLower.includes('dtf') && hasGangSheetUrls) {\n      productTypes.push('DTF Gang Sheet');\n      gangSheetRequired = true;\n    } else if (orderTypeLower.includes('uv')) {\n      productTypes.push('UV Stickers');\n    } else if (orderTypeLower.includes('dtf')) {\n      productTypes.push('DTF Transfer');\n    } else if (orderTypeLower.includes('sublimation')) {\n      productTypes.push('Sublimation');\n    } else {\n      productTypes.push('Custom Transfer');\n    }\n    \n    // Check for precut\n    if (orderTypeLower.includes('precut') || \n        orderTypeLower.includes('pre-cut') || \n        parsedData.precutQuantity > 0) {\n      precut = true;\n      \n      // Add precut variant to product type\n      productTypes = productTypes.map(pt => \n        pt.includes('Gang Sheet') ? pt : `${pt} (Pre-cut)`\n      );\n    }\n    \n    // Extract customer info\n    const customer = jiffyData.customer || {\n      email: 'orders@jiffy.com',\n      name: 'Jiffy',\n      company: 'Jiffy',\n      phone: '',\n      isB2B: true\n    };\n    \n    // Extract shipping address\n    const shipping = jiffyData.shipping || {};\n    const shippingAddress = {\n      name: shipping.name || customer.name,\n      firstName: shipping.firstName || '',\n      lastName: shipping.lastName || '',\n      company: shipping.company || '',\n      address1: shipping.address1 || '',\n      address2: shipping.address2 || '',\n      city: shipping.city || '',\n      province: shipping.province || shipping.state || '',\n      country: shipping.country || 'US',\n      zip: shipping.zip || shipping.postalCode || '',\n      phone: shipping.phone || customer.phone || '',\n      fullAddress: `${shipping.address1 || ''}${shipping.address2 ? ', ' + shipping.address2 : ''}, ${shipping.city || ''}, ${shipping.province || shipping.state || ''} ${shipping.zip || ''}`\n    };\n    \n    // Extract billing (usually same as shipping for Jiffy)\n    const billing = jiffyData.billing || shippingAddress;\n    \n    // Determine shipping option based on order type\n    let shippingOption = 'Ground';\n    let rushService = false;\n    let productionOption = 'Standard 2-3 Days';\n    \n    // Check for overnight shipping first (highest priority)\n    if (orderTypeLower.includes('overnight') || \n        orderTypeLower.includes('next day') ||\n        orderTypeLower.includes('1 day') ||\n        orderTypeLower.includes('1-day')) {\n      shippingOption = 'Overnight';\n      rushService = true;\n      productionOption = 'Super Rush 24 hrs';\n    }\n    // Then check for express shipping\n    else if (orderTypeLower.includes('express') ||\n             orderTypeLower.includes('expedited') ||\n             orderTypeLower.includes('2 day') ||\n             orderTypeLower.includes('2-day') ||\n             orderTypeLower.includes('priority')) {\n      shippingOption = 'Express';\n      rushService = true;\n      productionOption = 'Rush 1-2 Days';\n    }\n    // Check for rush service even if shipping is ground\n    else if (orderTypeLower.includes('rush')) {\n      rushService = true;\n      productionOption = 'Rush 1-2 Days';\n      // Shipping remains 'Ground' unless specified otherwise\n    }\n    \n    // Extract order tags\n    const orderTags = [];\n    if (rushService) orderTags.push('rush');\n    if (precut) orderTags.push('precut');\n    if (gangSheetRequired) orderTags.push('gang-sheet');\n    orderTags.push('b2b', 'jiffy', 'dropship');\n    \n    // Jiffy orders are always High priority\n    const priorityLevel = 'High';\n    \n    // Get financial data\n    const financial = jiffyData.financial || {};\n    const subtotal = parseFloat(financial.subtotal) || 0;\n    const shippingCost = 0; // Jiffy provides the shipping label, so cost is $0\n    const tax = parseFloat(financial.tax) || 0;\n    const total = parseFloat(financial.total) || subtotal + tax;\n    \n    // Process files and items\n    const allFiles = jiffyData.files || [];\n    const gangSheetUrls = jiffyData.gangSheetUrls || [];\n    const itemsArray = jiffyData.items || [];\n    const cutlineReferences = jiffyData.cutlineReferences || [];\n    \n    // Extract shipping label URL\n    const shippingLabelUrl = jiffyData.shipping_label_url || \n                            jiffyData.shippingLabel?.url || \n                            jiffyData.shipping_label_google_drive || '';\n    \n    // Filter out cutline references from files array\n    const files = allFiles.filter(file => {\n      const isReference = file.type === 'cutline_reference' || \n                         (file.url && file.url.includes('ref-')) ||\n                         (file.filename && !file.filename.includes('.'));\n      return !isReference;\n    });\n    \n    // Calculate total quantity from parsed data or items\n    let totalQuantity = parsedData.precutQuantity || itemsArray.length || files.length || 1;\n    \n    // Create order summary\n    const orderSummary = `Order: ${orderId}\\nDate: ${new Date().toLocaleDateString()}\\nSource: Jiffy (B2B Dropship)\\nPO Number: ${poNumber}\\nOrder Type: ${orderType}\\nShip To: ${shippingAddress.name}${shippingAddress.company ? ` - ${shippingAddress.company}` : ''}\\n${shippingAddress.fullAddress}\\nProducts: ${productTypes.join(', ')}\\nFiles: ${files.length}\\n${parsedData.precutQuantity ? `Pre-cut Quantity: ${parsedData.precutQuantity}\\n` : ''}${parsedData.totalPrintLength ? `Total Print Length: ${parsedData.totalPrintLength} inches\\n` : ''}${rushService ? `\u26a1 ${productionOption}\\n` : ''}${precut ? '\u2702\ufe0f Pre-cut Required\\n' : ''}${gangSheetRequired ? '\ud83d\udccf Gang Sheet Required\\n' : ''}\\nFulfillment: Ship - ${shippingOption}\\nShipping Date: ${jiffyData.shippingDate || 'TBD'}`;\n    \n    // Determine file status\n    const needsFile = files.length === 0 && gangSheetUrls.length === 0;\n    const fileStatus = jiffyData.fileStatus || (needsFile ? 'Awaiting Files' : 'All Files Received');\n    \n    // Create the canonical order structure\n    const orderCanon = {\n      // Identification\n      orderId,\n      submissionId,\n      source: 'jiffy',\n      jiffyPoNumber: poNumber,\n      \n      // Timestamps\n      orderDate: new Date().toISOString(),\n      createdAt: new Date().toISOString(),\n      updatedAt: new Date().toISOString(),\n      paidAt: new Date().toISOString(), // Jiffy orders are typically prepaid\n      fulfilledAt: null,\n      \n      // Customer data\n      customer: {\n        ...customer,\n        id: '',\n        ordersCount: 1,\n        totalSpent: total\n      },\n      \n      // Addresses\n      shipping: shippingAddress,\n      billing,\n      \n      // Financial data\n      financial: {\n        subtotal,\n        shipping: shippingCost,\n        tax,\n        total,\n        discountAmount: 0,\n        discountCodes: '',\n        currency: 'USD',\n        paymentStatus: jiffyData.paymentStatus || 'Paid',\n        paymentMethod: 'B2B Account',\n        refundedAmount: 0,\n        outstandingBalance: 0\n      },\n      \n      // Status\n      status: {\n        orderStatus: 'New',\n        fulfillmentStatus: null,\n        syncStatus: 'Success',\n        qcStatus: 'Not Started'\n      },\n      \n      // Options\n      options: {\n        rushService,\n        productionOption,\n        fulfillmentOption: 'Ship',\n        shippingOption,\n        precut,\n        gangSheetRequired,\n        needsFile,\n        notes: '',\n        customerNotes: '',\n        internalNotes: '',\n        tags: orderTags.join(','),\n        priorityLevel,\n        productTypes: productTypes.join(', '),\n        fileStatus,\n        isSamplePackOnly: false,\n        facility: null,\n        referralSource: 'B2B Partner',\n        orderSummary\n      },\n      \n      // Summary\n      summary: {\n        itemCount: gangSheetUrls.length || 1,\n        sourceUrl: `https://jiffy.com/orders/${poNumber}`\n      },\n      \n      // CRITICAL: Store attachment URLs separately for processing\n      _attachments: {\n        shippingLabelUrl,\n        shippingLabelFilename: shippingLabelUrl ? `JIFFY-${poNumber}-shipping-label.pdf` : ''\n      },\n      \n      // Metadata\n      meta: {\n        jiffy: {\n          rawData: jiffyData,\n          productTypes,\n          poNumber,\n          orderType,\n          shippingLabel: jiffyData.shippingLabel || null,\n          shippingLabelUrl,\n          trackingNumber: '',\n          gangSheetUrls,\n          cutlineReferences,\n          totalPrintLength: parsedData.totalPrintLength,\n          precutQuantity: parsedData.precutQuantity,\n          shippingDate: jiffyData.shippingDate\n        },\n        processedAt: new Date().toISOString()\n      }\n    };\n    \n    // Create order items from gang sheets with cutline references\n    const orderItems = [];\n    \n    // Process gang sheet URLs\n    if (gangSheetUrls && gangSheetUrls.length > 0) {\n      gangSheetUrls.forEach((url, index) => {\n        const fileName = extractFilenameFromUrl(url);\n        const dimensionData = extractDimensionsFromFilename(fileName);\n        const detectedProductType = detectProductTypeFromFilename(fileName);\n        const itemTitle = generateTitleFromFilename(fileName, detectedProductType);\n        \n        // Find cutline references for this gang sheet\n        const itemCutlineRefs = cutlineReferences.filter(ref => {\n          const refName = ref.filename || ref.name || extractFilenameFromUrl(ref.url || ref);\n          // Simple matching: assume cutlines are numbered or match the gang sheet index\n          return refName.includes(`${index + 1}of`) || \n                 refName.includes(`_${index + 1}`) ||\n                 refName.includes(`-${index + 1}`) ||\n                 (cutlineReferences.length === gangSheetUrls.length && \n                  cutlineReferences.indexOf(ref) === index);\n        });\n        \n        orderItems.push({\n          // Identification\n          itemUid: `${orderId}-${index + 1}`,\n          orderId: orderId,\n          lineItemId: `${index + 1}`,\n          source: 'jiffy',\n          \n          // Product info\n          productType: detectedProductType,\n          title: itemTitle,\n          name: itemTitle,\n          variantTitle: dimensionData.dimensions || 'Custom Size',\n          vendor: 'Transfer Superstars',\n          sku: `JIFFY-GS-${poNumber}-${index + 1}`,\n          \n          // Quantity and pricing\n          qty: 1,\n          price: subtotal > 0 ? subtotal / (gangSheetUrls.length || 1) : 0,\n          \n          // File info - MAIN GANG SHEET\n          fileUrl: url,\n          needsFile: false,\n          fileName: fileName,\n          originalFileUrl: url,\n          processedFileUrl: url,\n          previewUrl: url,\n          \n          // CRITICAL: Store cutline references for attachment processing\n          _attachments: {\n            cutlineRefs: itemCutlineRefs.map(ref => ({\n              url: typeof ref === 'string' ? ref : (ref.url || ''),\n              filename: typeof ref === 'string' ? extractFilenameFromUrl(ref) : \n                       (ref.filename || ref.name || extractFilenameFromUrl(ref.url || ''))\n            })).filter(ref => ref.url)\n          },\n          \n          // Dimensions\n          width: dimensionData.width,\n          height: dimensionData.height,\n          dimensions: dimensionData.dimensions,\n          originalDimensions: dimensionData.dimensions,\n          \n          // Specifications\n          isPrecut: precut,\n          precutQty: precut ? (parsedData.precutQuantity || 0) : 0,\n          isGangSheet: true,\n          gangSheetLength: parsedData.totalPrintLength || dimensionData.height || '',\n          \n          // Production options\n          addWeeding: false,\n          transferTape: false,\n          isSamplePack: false,\n          \n          // Status\n          itemStatus: 'pending',\n          fulfillmentStatus: null,\n          fulfillableQuantity: 1,\n          fulfillmentService: 'manual',\n          \n          // File quality\n          fileDpi: 300,\n          fileColorMode: 'RGB',\n          fileFormat: 'PNG',\n          fileDimensions: dimensionData.dimensions || '',\n          \n          // Tax and other flags\n          taxable: false,\n          giftCard: false,\n          \n          // Status\n          artworkQC: 'Pending',\n          qcNotes: '',\n          \n          // Facility\n          facility: null,\n          \n          // Meta with all references\n          meta: {\n            gangSheetUrl: url,\n            cutlineReferences: itemCutlineRefs,\n            itemIndex: index + 1,\n            totalItems: gangSheetUrls.length,\n            orderSource: 'jiffy',\n            processedAt: new Date().toISOString()\n          }\n        });\n      });\n    } else {\n      // Create a default item if no gang sheets\n      orderItems.push({\n        itemUid: `${orderId}-1`,\n        orderId: orderId,\n        lineItemId: '1',\n        source: 'jiffy',\n        productType: productTypes[0] || 'DTF Gang Sheet',\n        title: 'Jiffy Order Item - Awaiting Files',\n        name: 'Jiffy Order Item - Awaiting Files',\n        variantTitle: 'Custom',\n        vendor: 'Transfer Superstars',\n        sku: `JIFFY-DEFAULT-${poNumber}`,\n        qty: 1,\n        price: subtotal,\n        fileUrl: '',\n        needsFile: true,\n        fileName: '',\n        originalFileUrl: '',\n        processedFileUrl: '',\n        previewUrl: '',\n        _attachments: {\n          cutlineRefs: []\n        },\n        width: 0,\n        height: 0,\n        dimensions: '',\n        originalDimensions: '',\n        isPrecut: precut,\n        precutQty: parsedData.precutQuantity || 0,\n        isGangSheet: gangSheetRequired,\n        gangSheetLength: parsedData.totalPrintLength || '',\n        addWeeding: false,\n        transferTape: false,\n        isSamplePack: false,\n        itemStatus: 'needs_file',\n        fulfillmentStatus: null,\n        fulfillableQuantity: 1,\n        fulfillmentService: 'manual',\n        fileDpi: 300,\n        fileColorMode: 'RGB',\n        fileFormat: 'PNG',\n        fileDimensions: '',\n        taxable: false,\n        giftCard: false,\n        artworkQC: 'Pending',\n        qcNotes: '',\n        facility: null,\n        meta: {\n          orderSource: 'jiffy',\n          awaitingFiles: true,\n          processedAt: new Date().toISOString()\n        }\n      });\n    }\n    \n    // Return both order and items\n    return { \n      json: { \n        order: orderCanon,\n        items: orderItems\n      } \n    };\n    \n  } catch (error) {\n    console.error('Error parsing Jiffy order:', error);\n    return {\n      json: {\n        error: error.message,\n        rawData: item.json\n      }\n    };\n  }\n});"
      },
      "id": "e1b97ded-fdd5-4ba2-bf4e-5b197dfe4e9e",
      "name": "Function - Parse Jiffy",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        -60,
        80
      ],
      "onError": "continueRegularOutput"
    },
    {
      "parameters": {
        "errorMessage": "=Unrecognized order source: {{ $json.source }}\n\nThis workflow only supports: shopify, jotform, jiffy"
      },
      "id": "a574dd75-4b59-4859-bc23-4b447fe58318",
      "name": "Stop - Unrecognized Source",
      "type": "n8n-nodes-base.stopAndError",
      "typeVersion": 1,
      "position": [
        380,
        120
      ],
      "continueOnFail": true
    },
    {
      "parameters": {
        "jsCode": "// Store Record IDs - Fixed to use Parse Jiffy data\n// Get the ORIGINAL parsed data that contains orders and items\nconst parsedData = $('Fix Item Counts').all();\n\n// Get Airtable responses\nconst orderResponses = $('Upsert Orders').all();\nconst customerResponses = $('Upsert Customers').all();\n\nconsole.log(`Processing ${parsedData.length} parsed orders`);\nconsole.log('First parsed data:', parsedData[0]?.json);\n\n// Build lookup maps for Airtable records\nconst orderMap = new Map();\nconst customerMap = new Map();\n\n// Map orders by Order ID\norderResponses.forEach(response => {\n  if (!response.json.error && response.json.fields) {\n    const orderId = response.json.fields['Order ID'];\n    if (orderId) {\n      orderMap.set(orderId, response);\n    }\n  }\n});\n\n// Map customers by email\ncustomerResponses.forEach(response => {\n  if (!response.json.error && response.json.fields) {\n    const email = response.json.fields['Email'];\n    if (email) {\n      customerMap.set(email.toLowerCase(), response);\n    }\n  }\n});\n\n// Process the PARSED data, not the Airtable responses\nreturn parsedData.map((item, index) => {\n  const orderData = item.json.order || {};\n  const items = item.json.items || [];\n  const orderId = orderData.orderId;\n  \n  console.log(`Processing order ${orderId} with ${items.length} items`);\n  \n  // Find the Airtable records\n  let orderRecord = orderMap.get(orderId);\n  let customerRecord = null;\n  \n  // Try to find customer by email\n  const customerEmail = orderData.source === 'jiffy' ? \n    'orders@jiffy.com' : \n    (orderData.customer?.email || '');\n    \n  if (customerEmail) {\n    customerRecord = customerMap.get(customerEmail.toLowerCase());\n  }\n  \n  // Return the parsed data WITH the Airtable record IDs\n  return {\n    json: {\n      orderRecordId: orderRecord?.json?.id || null,\n      customerRecordId: customerRecord?.json?.id || null,\n      orderId: orderId,\n      order: orderData,  // This is the actual order data\n      items: items,      // These are the actual items\n      _debug: {\n        hasOrderRecord: !!orderRecord,\n        hasCustomerRecord: !!customerRecord,\n        itemCount: items.length,\n        source: orderData.source || 'unknown'\n      }\n    }\n  };\n});"
      },
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        1220,
        -560
      ],
      "id": "df701f5e-f93a-4d34-882c-b6936144e7bd",
      "name": "Store Record IDs",
      "onError": "continueRegularOutput"
    },
    {
      "parameters": {
        "jsCode": "// Add Record IDs to Items - Fixed Version with Cutline Attachments\nconst inputData = $input.all();\nconst results = [];\nlet processedItemCount = 0;\nlet skippedCount = 0;\nlet errorCount = 0;\n\nconsole.log(`Processing ${inputData.length} order inputs`);\nconsole.log('First input structure:', JSON.stringify(inputData[0]?.json, null, 2));\n\n// Helper function to validate file URL\nfunction isValidFileUrl(url) {\n  if (!url || typeof url !== 'string') return false;\n  \n  try {\n    const urlObj = new URL(url);\n    return urlObj.protocol === 'http:' || urlObj.protocol === 'https:';\n  } catch {\n    return false;\n  }\n}\n\n// Helper function to extract filename from URL\nfunction extractFilenameFromUrl(url) {\n  if (!url) return 'untitled';\n  \n  try {\n    // Check for filename parameter in Jiffy URLs\n    const filenameMatch = url.match(/filename=([^&]+)/);\n    if (filenameMatch) {\n      return decodeURIComponent(filenameMatch[1]);\n    }\n    \n    // Remove query parameters\n    const cleanUrl = url.split('?')[0];\n    // Get the last part of the path\n    const parts = cleanUrl.split('/');\n    const filename = parts[parts.length - 1] || 'untitled';\n    // Decode URI component\n    return decodeURIComponent(filename);\n  } catch (e) {\n    return 'untitled';\n  }\n}\n\n// Process each order\nfor (let index = 0; index < inputData.length; index++) {\n  const input = inputData[index];\n  \n  try {\n    // Check for errors\n    if (input.json.error) {\n      console.log(`Skipping order at index ${index} due to error: ${input.json.error}`);\n      results.push({ json: input.json });\n      errorCount++;\n      continue;\n    }\n    \n    // Extract required data\n    const orderRecordId = input.json.orderRecordId;\n    const customerRecordId = input.json.customerRecordId;\n    const orderId = input.json.orderId;\n    const orderData = input.json.order || {};\n    const items = input.json.items;\n    \n    // Validate required fields\n    if (!orderRecordId) {\n      console.error(`Missing orderRecordId at index ${index}`);\n      results.push({\n        json: {\n          error: 'Missing orderRecordId',\n          errorType: 'validation_error',\n          index,\n          inputData: input.json\n        }\n      });\n      errorCount++;\n      continue;\n    }\n    \n    if (!orderId) {\n      console.error(`Missing orderId at index ${index}`);\n      results.push({\n        json: {\n          error: 'Missing orderId',\n          errorType: 'validation_error',\n          index,\n          inputData: input.json\n        }\n      });\n      errorCount++;\n      continue;\n    }\n    \n    // Check if items exist and is an array\n    if (!items || !Array.isArray(items)) {\n      console.warn(`No items array found for order ${orderId} at index ${index}`);\n      \n      // Instead of skipping, create a placeholder item\n      const placeholderItem = {\n        json: {\n          // Order fields\n          'Order': [orderRecordId],\n          'Order ID': orderId,\n          'Customer': customerRecordId ? [customerRecordId] : [],\n          \n          // Item identifiers\n          'Line Item ID': `${orderId}-placeholder`,\n          'Product ID': '',\n          'Variant ID': '',\n          'SKU': 'NO-ITEMS',\n          \n          // Basic info\n          'Title': 'No Items Found',\n          'Name': 'Placeholder - Check Order Data',\n          'Qty': 0,\n          'Price': 0,\n          \n          // File info\n          'File URL': '',\n          'Original File URL': '',\n          'File Name': 'no-file',\n          'Needs File?': true,\n          \n          // Status\n          'Item Status': 'Error - No Items',\n          'Artwork QC': 'Not Started',\n          'QC Notes': 'No items found in order data',\n          \n          // Metadata\n          'Meta (JSON)': JSON.stringify({\n            error: 'No items array in input',\n            orderSource: orderData.source || 'unknown',\n            timestamp: new Date().toISOString()\n          }),\n          \n          // Processing info\n          'Processed At': new Date().toISOString()\n        }\n      };\n      \n      results.push(placeholderItem);\n      skippedCount++;\n      continue;\n    }\n    \n    if (items.length === 0) {\n      console.warn(`Empty items array for order ${orderId}`);\n      skippedCount++;\n      continue;\n    }\n    \n    console.log(`Processing ${items.length} items for order ${orderId} (${orderData.source || 'unknown source'})`);\n    \n    // Get shipping address from order data\n    const shipping = orderData.shipping || {};\n    const shippingCountry = shipping.country || shipping.countryCode || '';\n    const shippingState = shipping.state || shipping.provinceCode || '';\n    \n    // Process each item\n    items.forEach((item, itemIndex) => {\n      // IMPORTANT: Extract cutline references from _attachments\n      let cutlineAttachments = [];\n      if (item._attachments && item._attachments.cutlineRefs) {\n        cutlineAttachments = item._attachments.cutlineRefs;\n      }\n      \n      // Get cutline references - handle different data structures\n      let cutlineReferences = [];\n      \n      // Check various possible locations for cutline references\n      if (item.cutlineReferences && Array.isArray(item.cutlineReferences)) {\n        cutlineReferences = item.cutlineReferences;\n      } else if (item.meta?.jiffy?.cutlineReferences) {\n        cutlineReferences = item.meta.jiffy.cutlineReferences;\n      } else if (orderData.meta?.jiffy?.cutlineReferences) {\n        // Use order-level cutline references if item doesn't have any\n        cutlineReferences = orderData.meta.jiffy.cutlineReferences || [];\n      }\n      \n      // Create an array of matched cutline reference filenames\n      const matchedCutlineReferences = cutlineReferences.map(ref => \n        ref.filename || ref.url || ''\n      ).filter(Boolean);\n      \n      // Determine item status based on file validation\n      // For Jiffy orders, check if file URL exists and contains jiffy.com\n      let itemStatus = item.itemStatus || 'Pending Art';\n      const hasJiffyFile = item.fileUrl && item.fileUrl.includes('jiffy.com');\n      \n      if (!item.needsFile && (isValidFileUrl(item.fileUrl) || hasJiffyFile)) {\n        itemStatus = 'Ready for QC';\n      } else if (item.needsFile || !item.fileUrl) {\n        itemStatus = 'Pending Art';\n      }\n      \n      // Calculate dimensions - handle both numeric and string inputs\n      const width = parseFloat(item.width) || 0;\n      const height = parseFloat(item.height) || 0;\n      const dimensions = width && height ? `${width}\" x ${height}\"` : (item.dimensions || item.originalDimensions || '');\n      \n      // Build the item record\n      results.push({\n        json: {\n          // Linked records\n          'Order': [orderRecordId],\n          'Order ID': orderId,\n          'Customer': customerRecordId ? [customerRecordId] : [],\n          \n          // Item identifiers\n          'Line Item ID': item.lineItemId || item.id || `${orderId}-${itemIndex}`,\n          'Product ID': item.productId || '',\n          'Variant ID': item.variantId || '',\n          'SKU': item.sku || '',\n          \n          // IMPORTANT: Add itemUid for matching in Process Cutline Attachments\n          'itemUid': item.itemUid || `${orderId}-${itemIndex + 1}`,\n          \n          // Basic info\n          'Title': item.title || item.name || 'Untitled Item',\n          'Name': item.name || item.title || 'Untitled Item',\n          'Qty': item.qty || 1,\n          'Fulfillable Quantity': item.fulfillableQuantity || item.qty || 1,\n          'Price': 0, // Set to 0 for Jiffy orders as requested\n          \n          // File info\n          'File URL': item.fileUrl || '',\n          'Original File URL': item.originalFileUrl || item.fileUrl || '',\n          'File Name': item.fileName || item.filename || extractFilenameFromUrl(item.fileUrl) || 'no-file',\n          'Needs File?': item.needsFile !== undefined ? item.needsFile : !isValidFileUrl(item.fileUrl),\n          'File Validated': isValidFileUrl(item.fileUrl) || (item.fileUrl && item.fileUrl.includes('jiffy.com')),\n          \n          // Dimensions\n          'Width': width,\n          'Height': height,\n          'Original Dimensions': dimensions,\n          \n          // Product details\n          'Product Type': item.productType || 'DTF Transfers',\n          'Application': item.application || '',\n          'White Ink': item.whiteInk || '',\n          'Underbase': item.underbase || '',\n          \n          // Shipping\n          'Country': shippingCountry,\n          'State': shippingState,\n          \n          // Fulfillment\n          'Vendor': item.vendor || '',\n          'Fulfillment Service': item.fulfillmentService || 'manual',\n          'Fulfillment Status': item.fulfillmentStatus || null,\n          \n          // Status\n          'Item Status': itemStatus,\n          'Artwork QC': item.artworkQC || 'Pending',\n          'QC Notes': item.qcNotes || '',\n          \n          // Financial\n          'Taxable': item.taxable !== undefined ? item.taxable : false,\n          'Gift Card': item.giftCard || false,\n          \n          // Precut info\n          'Pre-cut?': item.isPrecut || false,\n          'Precut Qty': item.precutQty || item.precutQuantity || 0,\n          \n          // Cutline references\n          'Cutline References': matchedCutlineReferences.join(', '),\n          \n          // IMPORTANT: Store cutline attachments for later processing\n          'cutlineAttachments': cutlineAttachments,\n          \n          // Facility\n          'Facility': item.facility || null,\n          \n          // Metadata - FIXED to use correct order source\n          'Meta (JSON)': JSON.stringify({\n            cutlineReferences: matchedCutlineReferences,\n            orderSource: item.source || orderData.source || 'jiffy', // Use item source first, then order source, default to 'jiffy'\n            processedAt: new Date().toISOString()\n          }),\n          \n          // Timestamps\n          'Processed At': new Date().toISOString()\n        }\n      });\n\n      processedItemCount++;\n    });\n\n    console.log(`Processed ${items.length} items for order ${orderId}`);\n\n  } catch (error) {\n    console.error(`Error processing order at index ${index}:`, error.message);\n    results.push({\n      json: {\n        error: error.message,\n        errorType: 'item_processing_error',\n        index,\n        orderId: input.json.orderId || 'unknown',\n        orderSource: input.json.order?.source || 'unknown',\n        timestamp: new Date().toISOString(),\n        inputData: input.json\n      }\n    });\n    errorCount++;\n  }\n}\n\nconsole.log(`Processing complete: ${processedItemCount} items processed from ${inputData.length} orders, ${skippedCount} skipped, ${errorCount} errors`);\n\n// If no results were generated, return diagnostic information\nif (results.length === 0) {\n  console.warn('No items processed - returning diagnostic information');\n  \n  const diagnostics = inputData.map((item, idx) => ({\n    index: idx,\n    hasOrderRecordId: !!item.json.orderRecordId,\n    hasOrderId: !!item.json.orderId,\n    hasOrder: !!item.json.order,\n    orderSource: item.json.order?.source || 'unknown',\n    hasItems: !!item.json.items,\n    itemsIsArray: Array.isArray(item.json.items),\n    itemCount: Array.isArray(item.json.items) ? item.json.items.length : 0,\n    hasError: !!item.json.error,\n    errorMessage: item.json.error || null\n  }));\n  \n  return [{\n    json: {\n      message: 'No valid items to process',\n      summary: {\n        totalOrders: inputData.length,\n        itemsProcessed: processedItemCount,\n        ordersSkipped: skippedCount,\n        errors: errorCount\n      },\n      diagnostics: diagnostics,\n      timestamp: new Date().toISOString(),\n      troubleshooting: {\n        suggestion: 'Check if Store Record IDs is passing order and items data correctly',\n        expectedStructure: {\n          orderRecordId: 'string (Airtable record ID)',\n          orderId: 'string (Order ID)',\n          order: 'object with source property',\n          items: 'array of item objects'\n        }\n      }\n    }\n  }];\n}\n\nreturn results;"
      },
      "id": "bc5ebf8f-527f-47d7-8fde-f0c508a369e5",
      "name": "Add Record IDs to Items",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        1400,
        -560
      ],
      "onError": "continueErrorOutput"
    },
    {
      "parameters": {
        "jsCode": "// Get all items that were just created/updated in Airtable\nconst items = $input.all();\nconst fileRecords = [];\n\n// Helper function to extract filename from URL\nfunction extractFilenameFromUrl(url) {\n  if (!url) return 'Untitled';\n  \n  try {\n    // Extract the last part of the URL path\n    const urlParts = url.split('/');\n    const filename = urlParts[urlParts.length - 1];\n    \n    // Remove query parameters if present\n    return filename.split('?')[0] || 'Untitled';\n  } catch (e) {\n    return 'Untitled';\n  }\n}\n\n// Helper function to extract file format from URL\nfunction extractFileFormat(url) {\n  if (!url) return 'PNG';\n  \n  try {\n    // Extract filename first\n    const filename = extractFilenameFromUrl(url);\n    \n    // Get extension from filename\n    const parts = filename.split('.');\n    if (parts.length > 1) {\n      return parts[parts.length - 1].toUpperCase();\n    }\n    \n    // Fallback: try to extract from URL directly\n    const urlParts = url.toLowerCase().split('.');\n    if (urlParts.length > 1) {\n      const ext = urlParts[urlParts.length - 1].split('?')[0]; // Remove query params\n      return ext.toUpperCase();\n    }\n    \n    return 'PNG'; // Default fallback\n  } catch (e) {\n    return 'PNG';\n  }\n}\n\n// Helper function to determine if filename is a default product name\nfunction isDefaultProductName(name) {\n  if (!name) return true;\n  \n  const defaultNames = [\n    'DTF Transfer Online Gang Sheet Builder PRO for Clothing',\n    'DTF Transfer Online Gang Sheet Builder PRO',\n    'Gang Sheet Builder',\n    'Preview_preview',\n    'Preview',\n    'Processed',\n    'Untitled'\n  ];\n  \n  return defaultNames.some(defaultName => \n    name.toLowerCase().includes(defaultName.toLowerCase())\n  );\n}\n\n// Helper function to get appropriate filename\nfunction getFileName(itemFields, url, type = 'main') {\n  const fieldName = itemFields['File Name'] || itemFields['Title'] || '';\n  \n  // If it's a default product name, extract from URL\n  if (isDefaultProductName(fieldName)) {\n    const urlFilename = extractFilenameFromUrl(url);\n    \n    // Add suffix based on type if needed\n    if (type === 'processed' && !urlFilename.includes('300dpi')) {\n      return urlFilename.replace(/\\.(png|jpg|jpeg|pdf)$/i, '_300dpi.$1');\n    } else if (type === 'preview' && !urlFilename.includes('preview')) {\n      return urlFilename.replace(/\\.(png|jpg|jpeg|pdf)$/i, '_preview.$1');\n    }\n    \n    return urlFilename;\n  }\n  \n  // Otherwise use the field name with appropriate suffix\n  if (type === 'processed') {\n    return `${fieldName}_300dpi`;\n  } else if (type === 'preview') {\n    return `${fieldName}_preview`;\n  }\n  \n  return fieldName;\n}\n\n// Process items using for...of loop to allow continue\nfor (const item of items) {\n  let itemRecordId = null;\n  let orderRecordId = null;\n  \n  try {\n    // Skip error items\n    if (item.error || item.message) {\n      console.log(`Skipping item with error: ${item.message || item.error}`);\n      continue; // FIXED: Use continue instead of return\n    }\n    \n    itemRecordId = item.json.id;\n    const itemFields = item.json.fields;\n    \n    // FIXED: Get orderRecordId from the Airtable response\n    // The \"Orders\" field in the Airtable response contains the linked order record ID\n    if (itemFields['Orders'] && Array.isArray(itemFields['Orders']) && itemFields['Orders'].length > 0) {\n      orderRecordId = itemFields['Orders'][0];\n    }\n    \n    // Log for debugging if orderRecordId is still missing\n    if (!orderRecordId) {\n      console.warn(`No orderRecordId found for item ${itemRecordId}. Available fields:`, Object.keys(itemFields));\n    }\n    \n    // Log for debugging\n    console.log(`Processing item ${itemRecordId}, orderRecordId: ${orderRecordId}`);\n    \n    // Check if this item has files to create\n    if (itemFields['File URL'] && !itemFields['Needs File']) {\n      \n      // Build the main file record\n      fileRecords.push({\n        json: {\n          \"File Name\": getFileName(itemFields, itemFields['File URL'], 'main'),\n          \"URL\": itemFields['File URL'],\n          \"Attachment\": [{ \"url\": itemFields['File URL'] }],\n          \"Linked Item\": [itemRecordId],\n          \"Orders\": orderRecordId ? [orderRecordId] : [], // Use the correctly extracted orderRecordId\n          \"DPI\": itemFields['File DPI'] || 300,\n          \"Quality Control Status\": itemFields['Artwork QC'] === 'Approved' ? 'Approved' : 'Pending',\n          \"Meta (JSON)\": JSON.stringify({\n            source: itemFields['Meta (JSON)'] ? JSON.parse(itemFields['Meta (JSON)']).source : 'unknown',\n            originalUrl: itemFields['Original File URL'] || itemFields['File URL'],\n            processedUrl: itemFields['Processed File URL'],\n            previewUrl: itemFields['Preview URL'],\n            format: extractFileFormat(itemFields['File URL']), // FIXED: Extract from URL\n            dimensions: itemFields['File Dimensions'] || itemFields['Dimensions (in)'],\n            orderRecordId: orderRecordId,\n            colorSpace: itemFields['File Color Mode'] || 'RGB'\n          }),\n          \"Upload Date\": new Date().toISOString(),\n          \"Original Dimensions\": itemFields['File Dimensions'] || itemFields['Dimensions (in)'] || '',\n          \"File Format\": extractFileFormat(itemFields['File URL']) // FIXED: Extract from URL\n        }\n      });\n      \n      // Create additional file record for processed URL if it exists and is different\n      if (itemFields['Processed File URL'] && \n          itemFields['Processed File URL'] !== itemFields['File URL']) {\n        fileRecords.push({\n          json: {\n            \"File Name\": getFileName(itemFields, itemFields['Processed File URL'], 'processed'),\n            \"URL\": itemFields['Processed File URL'],\n            \"Attachment\": [{ \"url\": itemFields['Processed File URL'] }],\n            \"Linked Item\": [itemRecordId],\n            \"Orders\": orderRecordId ? [orderRecordId] : [],\n            \"DPI\": 300,\n            \"Quality Control Status\": 'Approved',\n            \"Meta (JSON)\": JSON.stringify({\n              source: itemFields['Meta (JSON)'] ? JSON.parse(itemFields['Meta (JSON)']).source : 'unknown',\n              type: 'processed',\n              originalFile: itemFields['File URL'],\n              orderRecordId: orderRecordId,\n              colorSpace: 'RGB'\n            }),\n            \"Upload Date\": new Date().toISOString(),\n            \"File Format\": extractFileFormat(itemFields['Processed File URL']), // FIXED: Extract from URL\n            \"Processed Date\": new Date().toISOString()\n          }\n        });\n      }\n      \n      // Create preview file record if it exists\n      if (itemFields['Preview URL'] && \n          itemFields['Preview URL'] !== itemFields['File URL'] &&\n          itemFields['Preview URL'] !== itemFields['Processed File URL']) {\n        fileRecords.push({\n          json: {\n            \"File Name\": getFileName(itemFields, itemFields['Preview URL'], 'preview'),\n            \"URL\": itemFields['Preview URL'],\n            \"Attachment\": [{ \"url\": itemFields['Preview URL'] }],\n            \"Linked Item\": [itemRecordId],\n            \"Orders\": orderRecordId ? [orderRecordId] : [],\n            \"DPI\": 72, // Preview images are typically lower DPI\n            \"Quality Control Status\": 'Approved',\n            \"Meta (JSON)\": JSON.stringify({\n              source: itemFields['Meta (JSON)'] ? JSON.parse(itemFields['Meta (JSON)']).source : 'unknown',\n              type: 'preview',\n              originalFile: itemFields['File URL'],\n              orderRecordId: orderRecordId,\n              colorSpace: 'RGB'\n            }),\n            \"Upload Date\": new Date().toISOString(),\n            \"File Format\": extractFileFormat(itemFields['Preview URL']) // FIXED: Extract from URL\n          }\n        });\n      }\n    }\n  } catch (error) {\n    console.error('Error preparing file record for item:', itemRecordId || 'unknown', error.message);\n  }\n}\n\n// Log summary\nconsole.log(`Prepared ${fileRecords.length} file records from ${items.length} items`);\n\nreturn fileRecords.length > 0 ? fileRecords : [{ json: { message: 'No files to create' } }];"
      },
      "id": "7cad7d82-df35-49dd-9261-558dd8797745",
      "name": "Prepare File Records",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        1960,
        -300
      ],
      "onError": "continueRegularOutput"
    },
    {
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "strict",
            "version": 1
          },
          "conditions": [
            {
              "id": "abc123",
              "leftValue": "={{ $json.URL }}",
              "rightValue": "No files to create",
              "operator": {
                "type": "string",
                "operation": "exists",
                "singleValue": true
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      },
      "id": "198349d6-9d4e-4d13-8547-7f11ce2e7be9",
      "name": "Filter Files",
      "type": "n8n-nodes-base.filter",
      "typeVersion": 2,
      "position": [
        2140,
        -300
      ]
    },
    {
      "parameters": {
        "authentication": "airtableOAuth2Api",
        "operation": "upsert",
        "base": {
          "__rl": true,
          "value": "appZdp18sltDYOs4s",
          "mode": "list",
          "cachedResultName": "Order Management",
          "cachedResultUrl": "https://airtable.com/appZdp18sltDYOs4s"
        },
        "table": {
          "__rl": true,
          "value": "tbl9a8Q2c0EikD6oY",
          "mode": "list",
          "cachedResultName": "Files",
          "cachedResultUrl": "https://airtable.com/appZdp18sltDYOs4s/tbl9a8Q2c0EikD6oY"
        },
        "columns": {
          "mappingMode": "defineBelow",
          "value": {
            "DPI": "={{ $json.DPI || \"\" }}",
            "File Name": "={{ $json[\"File Name\"] }}",
            "URL": "={{ $json.URL }}",
            "Attachment": "={{ $json.Attachment }}",
            "Linked Item": "={{ [$json[\"Linked Item\"][0]] }}",
            "Meta (JSON)": "={{ $json[\"Meta (JSON)\"] }}",
            "Original Dimensions": "={{ $json[\"Original Dimensions\"] }}",
            "File Format": "={{ $json[\"File Format\"] }}",
            "Resolution": "={{\n  (() => {\n    const raw = $json[\"Original Dimensions\"] || \"\";\n    const match = raw.match(/([\\d.]+)\\s*\"?\\s*[xX]\\s*([\\d.]+)\\s*\"?/);\n    if (!match) return \"\";\n\n    const dpi = 300;\n    const width = Math.round(parseFloat(match[1]) * dpi);\n    const height = Math.round(parseFloat(match[2]) * dpi);\n    return `${width} x ${height}`;\n  })()\n}}",
            "Upload Date": "2025-07-02T01:19:34"
          },
          "matchingColumns": [
            "File Name"
          ],
          "schema": [
            {
              "id": "id",
              "displayName": "id",
              "required": false,
              "defaultMatch": true,
              "display": true,
              "type": "string",
              "readOnly": true,
              "removed": false
            },
            {
              "id": "File ID",
              "displayName": "File ID",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "string",
              "readOnly": true,
              "removed": false
            },
            {
              "id": "File Name",
              "displayName": "File Name",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "File Format",
              "displayName": "File Format",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "options",
              "options": [
                {
                  "name": "PNG",
                  "value": "PNG"
                },
                {
                  "name": "JPG",
                  "value": "JPG"
                },
                {
                  "name": "PDF",
                  "value": "PDF"
                },
                {
                  "name": "AI",
                  "value": "AI"
                },
                {
                  "name": "PSD",
                  "value": "PSD"
                }
              ],
              "readOnly": false,
              "removed": false
            },
            {
              "id": "File Size",
              "displayName": "File Size",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "number",
              "readOnly": false,
              "removed": true
            },
            {
              "id": "Original Dimensions",
              "displayName": "Original Dimensions",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "URL",
              "displayName": "URL",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Shortened URL",
              "displayName": "Shortened URL",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": true
            },
            {
              "id": "Attachment",
              "displayName": "Attachment",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "array",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Linked Item",
              "displayName": "Linked Item",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "array",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "DPI",
              "displayName": "DPI",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "number",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Color Mode",
              "displayName": "Color Mode",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "options",
              "options": [
                {
                  "name": "RGB",
                  "value": "RGB"
                },
                {
                  "name": "CMYK",
                  "value": "CMYK"
                }
              ],
              "readOnly": false,
              "removed": true
            },
            {
              "id": "Meta (JSON)",
              "displayName": "Meta (JSON)",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Upload Date",
              "displayName": "Upload Date",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "dateTime",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Processed Date",
              "displayName": "Processed Date",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "dateTime",
              "readOnly": false,
              "removed": true
            },
            {
              "id": "Resolution",
              "displayName": "Resolution",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Has Transparency",
              "displayName": "Has Transparency",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "boolean",
              "readOnly": false,
              "removed": true
            },
            {
              "id": "Backup URL",
              "displayName": "Backup URL",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": true
            },
            {
              "id": "Autonumber",
              "displayName": "Autonumber",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "string",
              "readOnly": true,
              "removed": true
            }
          ],
          "options": {
            "typecast": true
          }
        },
        "options": {}
      },
      "id": "a28b3bc9-7a5c-4105-9070-949b85bd4af2",
      "name": "Airtable - Create Files",
      "type": "n8n-nodes-base.airtable",
      "typeVersion": 2,
      "position": [
        2300,
        -300
      ],
      "credentials": {
        "airtableOAuth2Api": {
          "name": "<your credential>"
        }
      },
      "onError": "continueRegularOutput"
    },
    {
      "parameters": {
        "jsCode": "// Check for Shipments - Process orders from Airtable\nconst items = $input.all();\n\nreturn items.map(item => {\n  const order = item.json;\n  \n  // Initialize shipment data\n  let hasShippingLabel = false;\n  let shippingLabelUrl = null;\n  let cutlineReferences = [];\n  let needsShipment = false;\n  let shipmentReady = false;\n  \n  try {\n    // Parse the Items Data (JSON) field - it's a stringified JSON\n    const itemsData = JSON.parse(order['Items Data (JSON)'] || '[]');\n    \n    // Check each item for shipping label and cutline references\n    itemsData.forEach(orderItem => {\n      // Check for shipping label URL in the item\n      if (orderItem.shippingLabelUrl) {\n        hasShippingLabel = true;\n        shippingLabelUrl = orderItem.shippingLabelUrl;\n      }\n      \n      // Collect cutline references\n      if (orderItem.cutlineReferences && Array.isArray(orderItem.cutlineReferences)) {\n        cutlineReferences = [...cutlineReferences, ...orderItem.cutlineReferences];\n      }\n      \n      // Also check in meta.jiffy if present\n      if (orderItem.meta?.jiffy?.shippingLabelUrl) {\n        hasShippingLabel = true;\n        shippingLabelUrl = orderItem.meta.jiffy.shippingLabelUrl;\n      }\n      \n      if (orderItem.meta?.jiffy?.cutlineReferences) {\n        cutlineReferences = [...cutlineReferences, ...orderItem.meta.jiffy.cutlineReferences];\n      }\n    });\n    \n    // Remove duplicate cutline references\n    cutlineReferences = cutlineReferences.filter((ref, index, self) => \n      index === self.findIndex(r => r.url === ref.url)\n    );\n    \n    // Determine if order needs shipment\n    const fulfillmentOption = order['Fulfillment Option'] || '';\n    const orderStatus = order['Order Status'] || '';\n    const fulfillmentStatus = order['Fulfillment Status'] || '';\n    const source = order['Source'] || '';\n    \n    // Order needs shipment if:\n    // 1. Fulfillment option is \"Ship\"\n    // 2. Order is not yet fulfilled\n    // 3. Has items to ship\n    needsShipment = (\n      fulfillmentOption.toLowerCase() === 'ship' &&\n      orderStatus !== 'Canceled' &&\n      orderStatus !== 'Refunded' &&\n      fulfillmentStatus !== 'Fulfilled' &&\n      itemsData.length > 0\n    );\n    \n    // Shipment is ready if:\n    // 1. Needs shipment\n    // 2. Has shipping label (for Jiffy orders)\n    // 3. Has shipping address\n    shipmentReady = needsShipment && (\n      (source.toLowerCase() === 'jiffy' && hasShippingLabel) ||\n      (source.toLowerCase() !== 'jiffy')\n    ) && order['Shipping Zip'];\n    \n  } catch (error) {\n    console.error('Error parsing items data:', error.message);\n  }\n  \n  // Return enriched order data\n  return {\n    json: {\n      // Original order data\n      ...order,\n      \n      // Shipment analysis\n      shipment: {\n        needsShipment,\n        shipmentReady,\n        hasShippingLabel,\n        shippingLabelUrl,\n        cutlineReferences,\n        \n        // Extract key shipping fields\n        orderId: order['Order ID'],\n        source: order['Source'],\n        fulfillmentOption: order['Fulfillment Option'],\n        shippingAddress: {\n          name: order['Shipping Name'] || order['Customer Name'],\n          address1: order['Shipping Address 1'],\n          address2: order['Shipping Address 2'],\n          city: order['Shipping City'],\n          state: order['Shipping State'],\n          zip: order['Shipping Zip'],\n          country: order['Shipping Country'] || 'US',\n          phone: order['Shipping Phone'] || order['Customer Phone']\n        },\n        \n        // Status\n        orderStatus: order['Order Status'],\n        fulfillmentStatus: order['Fulfillment Status'],\n        \n        // Jiffy specific\n        isJiffyOrder: order['Source']?.toLowerCase() === 'jiffy',\n        jiffyPoNumber: order['Jiffy PO Number'],\n        \n        // Metadata\n        checkedAt: new Date().toISOString()\n      },\n      \n      // Quick flags for routing\n      _needsShipment: needsShipment,\n      _shipmentReady: shipmentReady,\n      _hasShippingLabel: hasShippingLabel,\n      _isJiffyOrder: order['Source']?.toLowerCase() === 'jiffy'\n    }\n  };\n});"
      },
      "id": "9b96693e-f6f3-4e9d-b83e-8ee706560ddb",
      "name": "Check for Shipments",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        300,
        -220
      ],
      "onError": "continueRegularOutput"
    },
    {
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": false,
            "leftValue": "",
            "typeValidation": "loose",
            "version": 1
          },
          "conditions": [
            {
              "id": "def456",
              "leftValue": "={{ $json.fields[\"Fulfillment Option\"] }}",
              "rightValue": "Ship",
              "operator": {
                "type": "string",
                "operation": "equals"
              }
            }
          ],
          "combinator": "and"
        },
        "options": {
          "ignoreCase": true,
          "looseTypeValidation": true
        }
      },
      "id": "160a08af-edb4-4122-aec7-93e292380db7",
      "name": "Filter Shipments",
      "type": "n8n-nodes-base.filter",
      "typeVersion": 2,
      "position": [
        480,
        -220
      ],
      "onError": "continueRegularOutput"
    },
    {
      "parameters": {
        "authentication": "airtableOAuth2Api",
        "operation": "upsert",
        "base": {
          "__rl": true,
          "value": "appZdp18sltDYOs4s",
          "mode": "list",
          "cachedResultName": "Order Management",
          "cachedResultUrl": "https://airtable.com/appZdp18sltDYOs4s"
        },
        "table": {
          "__rl": true,
          "value": "tblcfyCosR8XXVH16",
          "mode": "list",
          "cachedResultName": "Shipments",
          "cachedResultUrl": "https://airtable.com/appZdp18sltDYOs4s/tblcfyCosR8XXVH16"
        },
        "columns": {
          "mappingMode": "defineBelow",
          "value": {
            "Delivered": false,
            "Signature Required": false,
            "Saturday Delivery": false,
            "Residential Address": false,
            "Claim Filed": false,
            "Label Cost": 0,
            "Package Weight": 0,
            "Insurance Amount": 0,
            "Claim Amount": 0,
            "Linked Order": "={{ [$json.id] }}",
            "Order ID": "={{ $json.fields[\"Order ID\"] }}",
            "Submission ID": "={{ $json.fields[\"Submission ID\"] }}",
            "Carrier": "UPS",
            "Service Type": "={{ $json.fields[\"Shipping Option\"] }}",
            "Package Dimensions": "25 x 25 x 2",
            "Label": "={{ [{ \"url\": $node[\"Google Drive\"].json.webContentLink }] }}",
            "Meta (JSON)": "={{ $json.fields[\"Meta (JSON)\"] }}",
            "Committed Shipping Date": "={{ $json.fields[\"Meta (JSON)\"].parseJson().jiffy.shippingDate }}",
            "Order Summary": "={{ $json.fields[\"Order Summary\"] }}"
          },
          "matchingColumns": [
            "Order ID"
          ],
          "schema": [
            {
              "id": "id",
              "displayName": "id",
              "required": false,
              "defaultMatch": true,
              "display": true,
              "type": "string",
              "readOnly": true,
              "removed": false
            },
            {
              "id": "Submission ID",
              "displayName": "Submission ID",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Order ID",
              "displayName": "Order ID",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Tracking Number",
              "displayName": "Tracking Number",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Linked Order",
              "displayName": "Linked Order",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "array",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Shipped Date",
              "displayName": "Shipped Date",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "dateTime",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Committed Shipping Date",
              "displayName": "Committed Shipping Date",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Carrier",
              "displayName": "Carrier",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "options",
              "options": [
                {
                  "name": "UPS",
                  "value": "UPS"
                },
                {
                  "name": "FedEx",
                  "value": "FedEx"
                },
                {
                  "name": "DHL",
                  "value": "DHL"
                },
                {
                  "name": "USPS",
                  "value": "USPS"
                }
              ],
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Service Type",
              "displayName": "Service Type",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Package Weight",
              "displayName": "Package Weight",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "number",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Package Dimensions",
              "displayName": "Package Dimensions",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Label Cost",
              "displayName": "Label Cost",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "number",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Delivered",
              "displayName": "Delivered",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "boolean",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Linked Files",
              "displayName": "Linked Files",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "array",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Label",
              "displayName": "Label",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "array",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Meta (JSON)",
              "displayName": "Meta (JSON)",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Order Summary",
              "displayName": "Order Summary",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Order Count",
              "displayName": "Order Count",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "string",
              "readOnly": true,
              "removed": false
            },
            {
              "id": "Insurance Amount",
              "displayName": "Insurance Amount",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "number",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Signature Required",
              "displayName": "Signature Required",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "boolean",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Saturday Delivery",
              "displayName": "Saturday Delivery",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "boolean",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Residential Address",
              "displayName": "Residential Address",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "boolean",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Delivery Instructions",
              "displayName": "Delivery Instructions",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Estimated Delivery",
              "displayName": "Estimated Delivery",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "dateTime",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Actual Delivery",
              "displayName": "Actual Delivery",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "dateTime",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Delivery Signature",
              "displayName": "Delivery Signature",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Return Label",
              "displayName": "Return Label",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "array",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Claim Filed",
              "displayName": "Claim Filed",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "boolean",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Claim Amount",
              "displayName": "Claim Amount",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "number",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Claim Status",
              "displayName": "Claim Status",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "options",
              "options": [
                {
                  "name": "Pending",
                  "value": "Pending"
                },
                {
                  "name": "Approved",
                  "value": "Approved"
                },
                {
                  "name": "Denied",
                  "value": "Denied"
                },
                {
                  "name": "Filed",
                  "value": "Filed"
                }
              ],
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Linked Order Items",
              "displayName": "Linked Order Items",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "array",
              "readOnly": false,
              "removed": false
            }
          ],
          "options": {
            "typecast": true
          }
        },
        "options": {}
      },
      "id": "12e7d3d0-96b2-4f73-8d15-9ca59ef5fa9b",
      "name": "Airtable - Create Shipment",
      "type": "n8n-nodes-base.airtable",
      "typeVersion": 2,
      "position": [
        720,
        -220
      ],
      "credentials": {
        "airtableOAuth2Api": {
          "name": "<your credential>"
        }
      },
      "onError": "continueRegularOutput"
    },
    {
      "parameters": {
        "authentication": "oAuth2",
        "select": "user",
        "user": {
          "__rl": true,
          "value": "@Chow",
          "mode": "username"
        },
        "text": ":package: New Order Alert!\n\n*Order ID:* {{ $('Store Record IDs').item.json.orderId }}\n*Source:* {{ $('Store Record IDs').item.json.order.source }}\n*Customer:* {{ $('Store Record IDs').item.json.order.customer.name }}\n*Email:* {{ $('Store Record IDs').item.json.order.customer.email }}\n*Phone:* {{ $('Store Record IDs').item.json.order.customer.phone }}\n*Items:* {{ $('Store Record IDs').item.json.order.summary.itemCount }}\n*Product Types:* {{ $('Store Record IDs').item.json.order.options.productTypes }}\n*Rush:* {{ $('Store Record IDs').item.json.order.options.rushService ? 'Yes \ud83d\udd25' : 'No' }}\n*Pre-cut:* {{ $('Store Record IDs').item.json.order.options.precut ? 'Yes \u2702\ufe0f' : 'No' }}\n*Gang Sheet:* {{ $('Store Record IDs').item.json.order.options.gangSheetRequired ? 'Yes \ud83d\udcd0' : 'No' }}\n*File Status:* {{ $('Store Record IDs').item.json.order.options.fileStatus }}\n*Total:* ${{ $('Store Record IDs').item.json.order.financial.total }}\n\n<https://airtable.com/appZdp18sltDYOs4s/tblXfXq9Gx1NUa33p/{{ $('Store Record IDs').item.json.orderRecordId }}|View Order in Airtable>",
        "otherOptions": {}
      },
      "id": "448e4d26-4157-4d5c-b640-3e908814201b",
      "name": "Slack - New order",
      "type": "n8n-nodes-base.slack",
      "typeVersion": 2,
      "position": [
        560,
        120
      ],
      "credentials": {
        "slackOAuth2Api": {
          "name": "<your credential>"
        }
      },
      "onError": "continueRegularOutput"
    },
    {
      "parameters": {
        "operation": "getAll",
        "simple": false,
        "filters": {
          "q": "subject:(DTF OR UV OR Sublimation OR PO OR Pre-Cut OR Pre-cut)",
          "sender": "dtforders@jiffyshirts.com"
        },
        "options": {
          "dataPropertyAttachmentsPrefixName": "data",
          "downloadAttachments": true
        }
      },
      "id": "70b55f8f-1949-468e-8995-ea784f8bfc8f",
      "name": "Jiffy Gmail Trigger",
      "type": "n8n-nodes-base.gmail",
      "typeVersion": 2.1,
      "position": [
        -1840,
        100
      ],
      "credentials": {
        "gmailOAuth2": {
          "name": "<your credential>"
        }
      },
      "onError": "continueRegularOutput"
    },
    {
      "parameters": {
        "url": "https://api.jotform.com/form/213408260643147/submissions",
        "authentication": "genericCredentialType",
        "genericAuthType": "httpHeaderAuth",
        "sendQuery": true,
        "queryParameters": {
          "parameters": [
            {
              "name": "limit",
              "value": "12"
            },
            {
              "name": "orderby",
              "value": "created_at,DESC"
            }
          ]
        },
        "options": {}
      },
      "id": "f23a2b8b-a494-4aca-a2e5-c83383d16fb0",
      "name": "HTTP DTF1",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4,
      "position": [
        -1580,
        -220
      ],
      "credentials": {
        "httpHeaderAuth": {
          "name": "<your credential>"
        }
      },
      "onError": "continueRegularOutput"
    },
    {
      "parameters": {
        "values": {
          "string": [
            {
              "name": "form_name",
              "value": "DTF Order Submission Form"
            },
            {
              "name": "form_layout",
              "value": "DTF Layout"
            },
            {
              "name": "source",
              "value": "jotform"
            }
          ]
        },
        "options": {}
      },
      "id": "8d1795f5-26df-438a-9626-dbfa869d705a",
      "name": "Tag DTF1",
      "type": "n8n-nodes-base.set",
      "typeVersion": 2,
      "position": [
        -1420,
        -220
      ]
    },
    {
      "parameters": {
        "url": "https://api.jotform.com/form/233115151476147/submissions",
        "authentication": "genericCredentialType",
        "genericAuthType": "httpHeaderAuth",
        "sendQuery": true,
        "queryParameters": {
          "parameters": [
            {
              "name": "limit",
              "value": "12"
            },
            {
              "name": "orderby",
              "value": "created_at,DESC"
            }
          ]
        },
        "options": {}
      },
      "id": "4742410a-fcce-4d68-889e-c0837a9739be",
      "name": "HTTP UV1",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4,
      "position": [
        -1580,
        -40
      ],
      "credentials": {
        "httpHeaderAuth": {
          "name": "<your credential>"
        }
      },
      "onError": "continueRegularOutput"
    },
    {
      "parameters": {
        "values": {
          "string": [
            {
              "name": "form_name",
              "value": "UV Sticker Order Submission Form"
            },
            {
              "name": "form_layout",
              "value": "UV Sticker Layout"
            },
            {
              "name": "source",
              "value": "jotform"
            }
          ]
        },
        "options": {}
      },
      "id": "2eb5a343-6c6f-42e3-b49a-a80ef2face78",
      "name": "Tag UV1",
      "type": "n8n-nodes-base.set",
      "typeVersion": 2,
      "position": [
        -1420,
        -40
      ]
    },
    {
      "parameters": {
        "mode": "passThrough"
      },
      "id": "3f6fe2cf-5a11-4275-a9a4-cfe27052e683",
      "name": "Merge Forms1",
      "type": "n8n-nodes-base.merge",
      "typeVersion": 1,
      "position": [
        -1220,
        -160
      ]
    },
    {
      "parameters": {
        "fieldToSplitOut": "content",
        "options": {}
      },
      "id": "b2084958-5495-48eb-b241-2a8ebbde61bc",
      "name": "Split Submissions1",
      "type": "n8n-nodes-base.itemLists",
      "typeVersion": 1,
      "position": [
        -1040,
        -160
      ],
      "onError": "continueRegularOutput"
    },
    {
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "strict",
            "version": 1
          },
          "conditions": [
            {
              "id": "filter_images",
              "leftValue": "={{ $json.fields['File Name'] || '' }}",
              "rightValue": "\\.(png|jpg|jpeg|webp|tiff)$",
              "operator": {
                "type": "string",
                "operation": "regex"
              }
            },
            {
              "id": "not_gang_sheet",
              "leftValue": "={{ ($json.fields['File Name'] || '').toLowerCase() }}",
              "rightValue": "gang",
              "operator": {
                "type": "string",
                "operation": "notContains"
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      },
      "id": "34629004-132c-41cc-96ce-85d83665144c",
      "name": "Filter Image Files",
      "type": "n8n-nodes-base.filter",
      "typeVersion": 2,
      "position": [
        2480,
        -300
      ],
      "onError": "continueRegularOutput"
    },
    {
      "parameters": {
        "url": "={{ $json.fields.Attachment[0].url }}",
        "options": {
          "response": {
            "response": {
              "responseFormat": "file"
            }
          },
          "timeout": 30000
        }
      },
      "id": "5a1d75f4-761a-4ef2-a323-48368b997279",
      "name": "Download File for Analysis",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        1960,
        -140
      ],
      "onError": "continueRegularOutput"
    },
    {
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "strict",
            "version": 1
          },
          "conditions": [
            {
              "id": "is_image_mime",
              "leftValue": "={{ $binary.data.mimeType }}",
              "rightValue": "image",
              "operator": {
                "type": "string",
                "operation": "contains"
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      },
      "id": "95fc60c2-5613-4762-a420-d508bb3dab87",
      "name": "Verify Image Type",
      "type": "n8n-nodes-base.filter",
      "typeVersion": 2,
      "position": [
        2120,
        -140
      ],
      "onError": "continueRegularOutput"
    },
    {
      "parameters": {
        "method": "POST",
        "url": "https://imageanalysis-sgpqdj2v7a-uc.a.run.app/analyze-image-url",
        "sendHeaders": true,
        "headerParameters": {
          "parameters": [
            {
              "name": "Content-Type",
              "value": "application/json"
            }
          ]
        },
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={\n  \"fileUrl\": \"{{ $json.fields.URL }}\"\n}",
        "options": {
          "response": {
            "response": {
              "responseFormat": "json"
            }
          },
          "timeout": 60000
        }
      },
      "id": "480540a5-a325-416a-8098-853fc2b9e33d",
      "name": "Analyze Image API",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        2300,
        -140
      ],
      "onError": "continueRegularOutput"
    },
    {
      "parameters": {
        "authentication": "airtableOAuth2Api",
        "operation": "upsert",
        "base": {
          "__rl": true,
          "value": "appZdp18sltDYOs4s",
          "mode": "list",
          "cachedResultName": "Order Management",
          "cachedResultUrl": "https://airtable.com/appZdp18sltDYOs4s"
        },
        "table": {
          "__rl": true,
          "value": "tbl9a8Q2c0EikD6oY",
          "mode": "list",
          "cachedResultName": "Files",
          "cachedResultUrl": "https://airtable.com/appZdp18sltDYOs4s/tbl9a8Q2c0EikD6oY"
        },
        "columns": {
          "mappingMode": "defineBelow",
          "value": {
            "id": "={{ $('Download File for Analysis').item.json.id }}",
            "File Size": 0,
            "Page Count": 0,
            "Resolution": "={{ $json.resolution.width }}x{{ $json.resolution.height }}",
            "DPI": "={{ $json.dpi }}",
            "Original Dimensions": "={{ $json.size.widthInches }}x{{ $json.size.heightInches }}",
            "Transparency": "={{ $json.transparency.hasTransparency }}",
            "File Improvement Suggestions": "={{ $json.printRecommendations }}",
            "QC Summary": "=Semi Transparent Pixels: {{ $json.transparency.hasSemiTransparentPixels }}\nSharpness Score: {{ $json.quality.sharpnessScore }}\nBlurry Edges: {{ $json.quality.hasBlurryEdges }}"
          },
          "matchingColumns": [
            "id"
          ],
          "schema": [
            {
              "id": "id",
              "displayName": "id",
              "required": false,
              "defaultMatch": true,
              "display": true,
              "type": "string",
              "readOnly": true
            },
            {
              "id": "File ID",
              "displayName": "File ID",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "string",
              "readOnly": true,
              "removed": false
            },
            {
              "id": "File Name",
              "displayName": "File Name",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "File Format",
              "displayName": "File Format",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "options",
              "options": [
                {
                  "name": "PNG",
                  "value": "PNG"
                },
                {
                  "name": "JPG",
                  "value": "JPG"
                },
                {
                  "name": "PDF",
                  "value": "PDF"
                },
                {
                  "name": "AI",
                  "value": "AI"
                },
                {
                  "name": "PSD",
                  "value": "PSD"
                }
              ],
              "readOnly": false,
              "removed": false
            },
            {
              "id": "File Size",
              "displayName": "File Size",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "number",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Original Dimensions",
              "displayName": "Original Dimensions",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "URL",
              "displayName": "URL",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Attachment",
              "displayName": "Attachment",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "array",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Linked Item",
              "displayName": "Linked Item",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "array",
              "readOnly": false,
              "removed": true
            },
            {
              "id": "DPI",
              "displayName": "DPI",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "number",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Color Mode",
              "displayName": "Color Mode",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "options",
              "options": [
                {
                  "name": "RGB",
                  "value": "RGB"
                },
                {
                  "name": "CMYK",
                  "value": "CMYK"
                }
              ],
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Transparency",
              "displayName": "Transparency",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "boolean",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Version Of",
              "displayName": "Version Of",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Meta (JSON)",
              "displayName": "Meta (JSON)",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Item Status",
              "displayName": "Item Status",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "string",
              "readOnly": true,
              "removed": false
            },
            {
              "id": "QC Summary",
              "displayName": "QC Summary",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "File Improvement Suggestions",
              "displayName": "File Improvement Suggestions",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Orders",
              "displayName": "Orders",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "array",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Upload Date",
              "displayName": "Upload Date",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "dateTime",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Processed Date",
              "displayName": "Processed Date",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "dateTime",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Resolution",
              "displayName": "Resolution",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Has Transparency",
              "displayName": "Has Transparency",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "boolean",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Approval Date",
              "displayName": "Approval Date",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "dateTime",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Processing Errors",
              "displayName": "Processing Errors",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "File Hash",
              "displayName": "File Hash",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Storage Location",
              "displayName": "Storage Location",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Backup URL",
              "displayName": "Backup URL",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Batches Table",
              "displayName": "Batches Table",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "array",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Shipments Table",
              "displayName": "Shipments Table",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "array",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Autonumber",
              "displayName": "Autonumber",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "string",
              "readOnly": true,
              "removed": false
            },
            {
              "id": "Quality Control Status",
              "displayName": "Quality Control Status",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "options",
              "options": [
                {
                  "name": "",
                  "value": ""
                }
              ],
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Page Count",
              "displayName": "Page Count",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "number",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Approved By",
              "displayName": "Approved By",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Rejection Reason",
              "displayName": "Rejection Reason",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            }
          ]
        },
        "options": {
          "typecast": true
        }
      },
      "id": "f38d4c2f-1cfd-40ac-8511-d70155039bc3",
      "name": "Update Files with Analysis",
      "type": "n8n-nodes-base.airtable",
      "typeVersion": 2,
      "position": [
        2480,
        -140
      ],
      "credentials": {
        "airtableOAuth2Api": {
          "name": "<your credential>"
        }
      },
      "onError": "continueRegularOutput"
    },
    {
      "parameters": {
        "jsCode": "const analysis = $json.analysis || {};\nconst fileRecord = $('Download File for Analysis').item.json;\nconst fileName = fileRecord.fields?.['File Name'] || 'Unknown';\nconst fileUrl = fileRecord.fields?.URL || '';\n\n// Get order context from earlier nodes\nlet orderId = '';\nlet customerEmail = '';\nlet orderRecordId = '';\n\ntry {\n  const orderContext = $('Store Record IDs').item.json;\n  orderId = orderContext.orderId || '';\n  customerEmail = orderContext.customerEmail || '';\n  orderRecordId = orderContext.orderRecordId || '';\n} catch (e) {\n  console.log('Could not get order context');\n}\n\nconst issues = [];\nlet qualityScore = 'Good';\n\n// Check DPI\nif (analysis.dpi && analysis.dpi < 300) {\n  issues.push(`Low DPI: ${analysis.dpi} (recommended 300+)`);\n  qualityScore = 'Poor';\n} else if (analysis.dpi && analysis.dpi < 250) {\n  issues.push(`Very low DPI: ${analysis.dpi} (minimum 300 required)`);\n  qualityScore = 'Poor';\n}\n\n// Check dimensions\nif (analysis.dimensions) {\n  const { widthInches, heightInches } = analysis.dimensions;\n  if (widthInches && widthInches > 22) {\n    issues.push(`Width too large: ${widthInches}\" (max 22\")`);\n    qualityScore = 'Poor';\n  }\n  if (heightInches && heightInches > 100) {\n    issues.push(`Height too large: ${heightInches}\" (max 100\")`);\n    qualityScore = 'Poor';\n  }\n  \n  // Check for very small images\n  if (widthInches && widthInches < 0.5) {\n    issues.push(`Very small width: ${widthInches}\" (may be too small to print)`);\n    qualityScore = qualityScore === 'Good' ? 'Fair' : qualityScore;\n  }\n  if (heightInches && heightInches < 0.5) {\n    issues.push(`Very small height: ${heightInches}\" (may be too small to print)`);\n    qualityScore = qualityScore === 'Good' ? 'Fair' : qualityScore;\n  }\n}\n\n// Check file size (if available)\nif (analysis.fileSize) {\n  const fileSizeMB = analysis.fileSize / (1024 * 1024);\n  if (fileSizeMB > 50) {\n    issues.push(`Large file size: ${Math.round(fileSizeMB)}MB (may cause processing delays)`);\n    qualityScore = qualityScore === 'Good' ? 'Fair' : qualityScore;\n  }\n}\n\n// Check transparency for DTF (should have transparency)\nif (analysis.hasTransparency === false && !fileName.toLowerCase().includes('gang')) {\n  issues.push('No transparency detected - DTF transfers typically need transparent backgrounds');\n  qualityScore = qualityScore === 'Good' ? 'Fair' : qualityScore;\n}\n\n// Check for other quality indicators\nif (analysis.colorSpace && analysis.colorSpace !== 'RGB') {\n  issues.push(`Color space: ${analysis.colorSpace} (RGB recommended for DTF)`);\n}\n\nif (analysis.bitDepth && analysis.bitDepth < 8) {\n  issues.push(`Low bit depth: ${analysis.bitDepth}-bit (8-bit minimum recommended)`);\n  qualityScore = 'Poor';\n}\n\nreturn [{\n  json: {\n    fileRecordId: fileRecord.id,\n    fileName: fileName,\n    fileUrl: fileUrl,\n    orderId: orderId,\n    customerEmail: customerEmail,\n    orderRecordId: orderRecordId,\n    hasIssues: issues.length > 0,\n    issues: issues,\n    analysis: analysis,\n    needsReview: issues.length > 0,\n    qualityScore: qualityScore,\n    issueCount: issues.length,\n    severity: qualityScore === 'Poor' ? 'High' : qualityScore === 'Fair' ? 'Medium' : 'Low'\n  }\n}];"
      },
      "id": "a8682ae4-9737-4a20-bf06-9faedcbd30a3",
      "name": "Detect File Issues",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        1280,
        220
      ],
      "onError": "continueRegularOutput"
    },
    {
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "strict",
            "version": 1
          },
          "conditions": [
            {
              "id": "has_issues",
              "leftValue": "={{ $json.hasIssues }}",
              "rightValue": true,
              "operator": {
                "type": "boolean",
                "operation": "equal"
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      },
      "id": "291b99c3-0172-4024-950a-aeca8b9a3ff5",
      "name": "Filter Files with Issues",
      "type": "n8n-nodes-base.filter",
      "typeVersion": 2,
      "position": [
        1440,
        220
      ],
      "onError": "continueRegularOutput"
    },
    {
      "parameters": {
        "authentication": "oAuth2",
        "select": "channel",
        "channelId": {
          "__rl": true,
          "value": "C07BENQV8HQ",
          "mode": "list",
          "cachedResultName": "#alerts"
        },
        "text": "=\ud83d\udea8 **File Quality Issues Detected**\n\n*Order:* {{ $json.orderId }}\n*Customer:* {{ $json.customerEmail }}\n*File:* {{ $json.fileName }}\n*Severity:* {{ $json.severity }}\n\n**Issues Found ({{ $json.issueCount }}):**\n{{ $json.issues.map(issue => `\u2022 ${issue}`).join('\\n') }}\n\n*Quality Score:* {{ $json.qualityScore }}\n\n<https://airtable.com/appZdp18sltDYOs4s/tbl9a8Q2c0EikD6oY/{{ $json.fileRecordId }}|\ud83d\udd0d Review File in Airtable>",
        "otherOptions": {}
      },
      "id": "de2eadfe-b43b-4e10-a4e2-c2ff0f0e4d87",
      "name": "Slack - File Issues Alert",
      "type": "n8n-nodes-base.slack",
      "typeVersion": 2,
      "position": [
        760,
        120
      ],
      "credentials": {
        "slackOAuth2Api": {
          "name": "<your credential>"
        }
      },
      "onError": "continueRegularOutput"
    },
    {
      "parameters": {
        "jsCode": "// Get the analysis results from Detect File Issues\nconst analysisResult = $input.all()[0].json;\n\n// Find the corresponding Order Item record to update\n// We need to find the item that has this file URL\nconst fileUrl = analysisResult.fileUrl;\nconst orderId = analysisResult.orderId;\n\n// Get all order items that were created in this workflow\nlet orderItems = [];\ntry {\n  orderItems = $('Upsert Order Items').all();\n} catch (e) {\n  console.log('Could not access order items node');\n}\n\n// Find the matching order item by file URL or order ID\nconst matchingItem = orderItems.find(item => {\n  const itemFields = item.json.fields || {};\n  const itemFileUrl = itemFields['File URL'] || itemFields['Original File URL'];\n  const itemOrderId = itemFields['Orders'] || [];\n  \n  return itemFileUrl === fileUrl || \n         (orderId && itemOrderId.some(id => id.includes(orderId)));\n});\n\nif (!matchingItem) {\n  console.log(`No matching order item found for file: ${fileUrl}`);\n  return [{ json: { message: 'No matching order item found', skip: true } }];\n}\n\nconst itemRecordId = matchingItem.json.id;\nconst qcStatus = analysisResult.hasIssues ? 'Fix Needed' : 'Approved';\nconst qcNotes = analysisResult.issues.length > 0 ? \n  `Automated analysis: ${analysisResult.issues.join('; ')}` : \n  'Automated analysis passed - no issues detected';\n\nreturn [{\n  json: {\n    itemRecordId: itemRecordId,\n    qcStatus: qcStatus,\n    qcNotes: qcNotes,\n    qualityScore: analysisResult.qualityScore,\n    fileQcStatus: analysisResult.hasIssues ? 'Issues Detected' : 'Quality OK'\n  }\n}];"
      },
      "id": "5bb1d65b-cd2f-40d2-982d-3d8236b4f156",
      "name": "Prepare Order Item Update",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        1620,
        300
      ],
      "onError": "continueRegularOutput"
    },
    {
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "strict",
            "version": 1
          },
          "conditions": [
            {
              "id": "not_skip",
              "leftValue": "={{ $json.skip }}",
              "rightValue": true,
              "operator": {
                "type": "boolean",
                "operation": "notEqual"
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      },
      "id": "02701b25-4e15-4084-92bb-30511e0298b1",
      "name": "Filter Valid Updates",
      "type": "n8n-nodes-base.filter",
      "typeVersion": 2,
      "position": [
        1800,
        300
      ],
      "onError": "continueRegularOutput"
    },
    {
      "parameters": {
        "authentication": "airtableOAuth2Api",
        "operation": "update",
        "base": {
          "__rl": true,
          "value": "appZdp18sltDYOs4s",
          "mode": "list",
          "cachedResultName": "Order Management",
          "cachedResultUrl": "https://airtable.com/appZdp18sltDYOs4s"
        },
        "table": {
          "__rl": true,
          "value": "tblTN1vUIpu6HHqEL",
          "mode": "list",
          "cachedResultName": "Order Items",
          "cachedResultUrl": "https://airtable.com/appZdp18sltDYOs4s/tblTN1vUIpu6HHqEL"
        },
        "columns": {
          "mappingMode": "defineBelow",
          "value": {
            "id": "={{ $json.itemRecordId }}",
            "Artwork QC": "={{ $json.qcStatus }}",
            "QC Notes": "={{ $json.qcNotes }}"
          },
          "matchingColumns": [
            "id"
          ],
          "schema": [
            {
              "id": "id",
              "displayName": "id",
              "required": false,
              "defaultMatch": true,
              "display": true,
              "type": "string",
              "readOnly": true
            }
          ]
        },
        "options": {
          "typecast": true
        }
      },
      "id": "2eea7133-abdf-4952-a82b-d9c7ad2647a3",
      "name": "Update Order Item QC",
      "type": "n8n-nodes-base.airtable",
      "typeVersion": 2,
      "position": [
        1120,
        -160
      ],
      "credentials": {
        "airtableOAuth2Api": {
          "name": "<your credential>"
        }
      },
      "onError": "continueRegularOutput"
    },
    {
      "parameters": {
        "jsCode": "// Merge the analysis results back to continue normal workflow\n// This ensures the Slack notification gets the order data it needs\n\n// Get the original order data from earlier in the workflow\nlet orderData = {};\ntry {\n  orderData = $('Store Record IDs').item.json;\n} catch (e) {\n  console.log('Could not get order data');\n}\n\n// Pass through the order data for the final Slack notification\nreturn [{\n  json: {\n    ...orderData,\n    imageAnalysisComplete: true,\n    analysisTimestamp: new Date().toISOString()\n  }\n}];"
      },
      "id": "cef1ed04-f4b3-4a8a-b64c-2de8a6d719dd",
      "name": "Merge Analysis Complete",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        1040,
        120
      ],
      "onError": "continueRegularOutput"
    },
    {
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "strict",
            "version": 2
          },
          "conditions": [
            {
              "id": "bc2d26d8-7dd9-401d-b4e9-88776f1c6990",
              "leftValue": "={{ $node[\"Jiffy Gmail Trigger\"].json.subject }}",
              "rightValue": "Re:",
              "operator": {
                "type": "string",
                "operation": "notStartsWith"
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      },
      "type": "n8n-nodes-base.filter",
      "typeVersion": 2.2,
      "position": [
        -1240,
        100
      ],
      "id": "39adae98-a89b-40a8-9f98-3ad9097d0af9",
      "name": "Filter2"
    },
    {
      "parameters": {
        "html": "<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n  <meta charset=\"UTF-8\">\n  <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n  <title>Order Details</title>\n  <style>\n    /* Base styling that works with Gmail HTML */\n    body {\n      font-family: 'Helvetica Neue', Arial, sans-serif;\n      line-height: 1.5;\n      color: #333;\n      margin: 0;\n      padding: 20px;\n      background-color: white;\n    }\n    \n    /* Container for the whole document */\n    .wrapper {\n      max-width: 800px;\n      margin: 0 auto;\n      border: 1px solid #e1e1e1;\n      border-radius: 5px;\n      padding: 20px;\n      box-shadow: 0 2px 5px rgba(0,0,0,0.05);\n    }\n    \n    /* Style existing Gmail HTML elements */\n    h1, h2, h3, h4, h5, h6 {\n      color: #2c3e50;\n      margin-top: 20px;\n      margin-bottom: 10px;\n    }\n    \n    p {\n      margin: 8px 0;\n    }\n    \n    /* Gmail tends to use <p> tags a lot */\n    p:empty {\n      display: none;\n    }\n    \n    /* Highlight PO Number */\n    p:contains(\"PO Number:\") {\n      font-size: 18px;\n      font-weight: bold;\n      background-color: #f5f5f5;\n      padding: 8px;\n      border-radius: 4px;\n      margin-top: 20px;\n      margin-bottom: 15px;\n    }\n    \n    /* Highlight delivery information */\n    p:contains(\"Delivery address:\") {\n      font-weight: bold;\n      margin-top: 15px;\n    }\n    \n    p:contains(\"Delivery address:\") + p,\n    p:contains(\"Delivery address:\") + p + p,\n    p:contains(\"Delivery address:\") + p + p + p {\n      background-color: #f9f9f9;\n      padding: 5px 10px;\n      margin-left: 15px;\n      border-left: 3px solid #3498db;\n    }\n    \n    /* Highlight shipping date */\n    p:contains(\"Committed Shipping Date:\") {\n      font-weight: bold;\n      color: #e74c3c;\n    }\n    \n    /* Style section headers */\n    p:contains(\"-----------\") {\n      border-bottom: 2px solid #f0f0f0;\n      padding-bottom: 5px;\n      margin-top: 20px;\n    }\n    \n    /* Style links */\n    a {\n      color: #3498db;\n      text-decoration: none;\n      word-break: break-all;\n    }\n    \n    a:hover {\n      text-decoration: underline;\n    }\n    \n    /* Style links (download links usually) */\n    p:contains(\"Download\") {\n      background-color: #f8f9fa;\n      padding: 8px;\n      border-radius: 4px;\n      margin: 10px 0;\n    }\n    \n    /* Footer */\n    .footer {\n      margin-top: 30px;\n      padding-top: 15px;\n      border-top: 1px solid #f5f5f5;\n      text-align: center;\n      font-size: 12px;\n      color: #7f8c8d;\n    }\n    \n    /* Print styles */\n    @media print {\n      body {\n        padding: 0;\n      }\n      \n      .wrapper {\n        border: none;\n        box-shadow: none;\n      }\n      \n      a {\n        color: #000;\n      }\n    }\n  </style>\n</head>\n<body>\n  <div class=\"wrapper\">\n   {{ $node[\"Jiffy Gmail Trigger\"].json.textAsHtml }}\n    \n    <!-- Add a footer -->\n    <div class=\"footer\">\n      <p>Generated on {{ $now }}</p>\n    </div>\n  </div>\n</body>\n</html>"
      },
      "type": "n8n-nodes-base.html",
      "typeVersion": 1.2,
      "position": [
        -1100,
        100
      ],
      "id": "2fdf708e-f562-42de-9904-70319d374735",
      "name": "HTML",
      "notesInFlow": true,
      "onError": "continueRegularOutput"
    },
    {
      "parameters": {
        "jsCode": "// Format HTML node - processes Gmail HTML content and extracts Jiffy order information\n// This version includes fix for pre-cut orders where anchor text equals the URL\n\n// Get Google Drive share link from previous node\nconst googleDriveShareLink = $('Google Drive').first()?.json?.webContentLink || null;\n\n// Helper function to extract filename from URL\nfunction extractFilenameFromUrl(url) {\n  if (!url) return '';\n  \n  try {\n    // Look for filename parameter in URL\n    const match = url.match(/filename=([^&]+)/);\n    if (match && match[1]) {\n      return decodeURIComponent(match[1]);\n    }\n    \n    // Otherwise extract the last part of the URL path\n    const urlParts = url.split('/');\n    const filename = urlParts[urlParts.length - 1];\n    return filename.split('?')[0] || '';\n  } catch (e) {\n    return url; // Return full URL if extraction fails\n  }\n}\n\n// Extract basic order information from HTML\nconst extractBasicInfo = html => {\n  const poMatch = html.match(/PO Number:\\s*(\\d+)/);\n  const orderTypeMatch = html.match(/Order Type:\\s*([^<]+)/);\n  const shippingDateMatch = html.match(/Committed Shipping Date:\\s*([^<]+)/);\n  const addressMatch = html.match(/Delivery address:<\\/p>\\s*<p>([^<]+)<\\/p>\\s*<p>([^<]+)<\\/p>\\s*<p>([^<]+)<\\/p>/);\n  \n  return {\n    poNumber: poMatch ? poMatch[1] : '',\n    orderType: orderTypeMatch ? orderTypeMatch[1].trim() : '',\n    shippingDate: shippingDateMatch ? shippingDateMatch[1].trim() : '',\n    addressParts: addressMatch ? {\n      line1: addressMatch[1],\n      line2: addressMatch[2],\n      line3: addressMatch[3]\n    } : null\n  };\n};\n\nconst parseAddress = (addressParts) => {\n  if (!addressParts) return null;\n  \n  // Parse line3 for city, state, zip\n  const cityStateZip = addressParts.line3.match(/^([^,]+),\\s*([A-Z]{2})\\s+(\\d{5}(?:-\\d{4})?)$/);\n  \n  return {\n    name: addressParts.line1 || '',\n    company: 'Jiffy',\n    address1: addressParts.line2 || '',\n    city: cityStateZip ? cityStateZip[1] : '',\n    state: cityStateZip ? cityStateZip[2] : '',\n    zip: cityStateZip ? cityStateZip[3] : '',\n    country: 'US',\n    countryCode: 'US'\n  };\n};\n\nconst extractFileInfo = html => {\n  const links = [];\n  const fileDetails = [];\n  \n  (html.match(/<a href=\\\"([^\\\"]+)\\\">([^<]+)<\\/a>/g) || []).forEach(m => {\n    const urlMatch = m.match(/<a href=\\\"([^\\\"]+)\\\">([^<]+)<\\/a>/);\n    if (urlMatch) {\n      const url = urlMatch[1];\n      const text = urlMatch[2];\n      \n      if (url.includes('jiffy.com')) {\n        links.push(url);\n        \n        // Check if text contains dimensions (regular orders)\n        if (text.includes('x') && /\\d+/.test(text) && !text.startsWith('http')) {\n          fileDetails.push({\n            url: url,\n            name: text,\n            dimensions: text.match(/(\\d+(?:\\.\\d+)?)\\s*x\\s*(\\d+(?:\\.\\d+)?)/)?.[0] || ''\n          });\n        } else {\n          // For pre-cut orders where text is the URL, extract dimensions from filename\n          const filenameMatch = url.match(/filename=([^&]+)/);\n          if (filenameMatch) {\n            const filename = decodeURIComponent(filenameMatch[1]);\n            const dimMatch = filename.match(/(\\d+(?:\\.\\d+)?)\\s*x\\s*(\\d+(?:\\.\\d+)?)\\s*in/i);\n            \n            fileDetails.push({\n              url: url,\n              name: filename,\n              dimensions: dimMatch ? `${dimMatch[1]}x${dimMatch[2]}` : ''\n            });\n          }\n        }\n      }\n    }\n  });\n  \n  // Also process cutline references\n  (html.match(/<a href=\\\"([^\\\"]+imgix[^\\\"]+)\\\">([^<]+)<\\/a>/g) || []).forEach(m => {\n    const urlMatch = m.match(/<a href=\\\"([^\\\"]+)\\\">([^<]+)<\\/a>/);\n    if (urlMatch) {\n      const url = urlMatch[1];\n      const dlMatch = url.match(/dl=([^&]+)/);\n      const filename = dlMatch ? decodeURIComponent(dlMatch[1]) : '';\n      \n      fileDetails.push({\n        url: url,\n        filename: filename || url.split('/').pop().split('?')[0],\n        type: 'cutline_reference'\n      });\n    }\n  });\n  \n  return { links, fileDetails };\n};\n\nconst extractItemsFromSection = (sectionHtml) => {\n  const items = [];\n  const lines = sectionHtml.split(/<\\/p>|<br\\/>/);\n  \n  lines.forEach(line => {\n    const itemMatch = line.match(/([^(]+)\\((\\d+)\\)/);\n    if (itemMatch) {\n      const name = itemMatch[1].trim();\n      const quantity = parseInt(itemMatch[2]);\n      const dimMatch = name.match(/(\\d+(?:\\.\\d+)?)\\s*x\\s*(\\d+(?:\\.\\d+)?)/);\n      \n      items.push({\n        name: name,\n        quantity: quantity,\n        dimensions: dimMatch ? dimMatch[0] : '',\n        productType: line.includes('UV') ? 'UV DTF' : 'DTF Transfers'\n      });\n    }\n  });\n  \n  return items;\n};\n\nconst extractSectionInfo = html => {\n  const sections = {};\n  \n  const preCutDTFMatch = html.match(/<p>Pre-Cut DTF<br\\/>-----------<\\/p>[\\s\\S]*?(?=<p>Pre-Cut UV DTF|$)/);\n  if (preCutDTFMatch) {\n    sections.preCutDTF = {\n      raw: preCutDTFMatch[0].trim(),\n      items: extractItemsFromSection(preCutDTFMatch[0])\n    };\n  }\n  \n  const preCutUVDTFMatch = html.match(/<p>Pre-Cut UV DTF<br\\/>--------------<\\/p>[\\s\\S]*?(?=$)/);\n  if (preCutUVDTFMatch) {\n    sections.preCutUVDTF = {\n      raw: preCutUVDTFMatch[0].trim(),\n      items: extractItemsFromSection(preCutUVDTFMatch[0])\n    };\n  }\n  \n  return sections;\n};\n\nconst calculateOrderTotals = (items) => {\n  const pricing = {\n    'DTF Transfers': 0.05,\n    'UV DTF': 0.08,\n    'Pre-cut': 2.00\n  };\n  \n  let subtotal = 0;\n  \n  items.forEach(item => {\n    if (item.dimensions) {\n      const [width, height] = item.dimensions.split('x').map(d => parseFloat(d));\n      const sqInches = width * height;\n      const basePrice = sqInches * (pricing[item.productType] || 0.05);\n      const precutPrice = item.name.toLowerCase().includes('pre-cut') ? pricing['Pre-cut'] : 0;\n      \n      subtotal += (basePrice + precutPrice) * item.quantity;\n    }\n  });\n  \n  return {\n    subtotal: subtotal,\n    shipping: 0.00,\n    tax: 0,\n    total: subtotal\n  };\n};\n\n// Process each item\nreturn items.map(item => {\n  const fullHtml = item.json.html || item.json.textAsHtml || '';\n  const email = item.json;\n  \n  // Extract just the content inside the wrapper div to avoid CSS interference\n  const wrapperMatch = fullHtml.match(/<div class=\"wrapper\">([\\s\\S]*?)<\\/div>\\s*<\\/body>/);\n  const html = wrapperMatch ? wrapperMatch[1] : fullHtml;\n  \n  // Extract all information\n  const basicInfo = extractBasicInfo(html);\n  const fileInfo = extractFileInfo(html);\n  const sections = extractSectionInfo(html);\n  const shippingAddress = parseAddress(basicInfo.addressParts);\n  \n  // Combine all items from different sections\n  const allItems = [\n    ...(sections.preCutDTF?.items || []),\n    ...(sections.preCutUVDTF?.items || [])\n  ];\n  \n  // Calculate totals\n  const totals = calculateOrderTotals(allItems);\n  \n  // Create the order ID\n  const orderId = `JIFFY-${basicInfo.poNumber}`;\n  const submissionId = `jiffy-${Date.now()}`;\n  \n  // Determine rush service\n  const rushService = basicInfo.orderType.toLowerCase().includes('rush') ? 'Rush 1-2 Days' : null;\n  \n  // Build shipping label info\n  const shippingLabelInfo = googleDriveShareLink ? \n    { url: googleDriveShareLink, filename: extractFilenameFromUrl(googleDriveShareLink) } : \n    null;\n  \n  // Parse sections and extract more detailed info\n  const parseSections = (html) => {\n    const result = {\n      orderType: '',\n      gangSheetUrls: [],\n      cutlineReferences: [],\n      precutQuantity: 0,\n      totalPrintLength: ''\n    };\n    \n    // Extract order type\n    const orderTypeMatch = html.match(/Order Type:\\s*([^<]+)/);\n    if (orderTypeMatch) {\n      result.orderType = orderTypeMatch[1].trim();\n    }\n    \n    // Extract pre-cut quantities\n    const precutMatches = html.match(/Pre-cut quantity:\\s*(\\d+)/gi);\n    if (precutMatches) {\n      precutMatches.forEach(match => {\n        const qtyMatch = match.match(/(\\d+)/);\n        if (qtyMatch) {\n          result.precutQuantity += parseInt(qtyMatch[1]);\n        }\n      });\n    }\n    \n    // Extract total print lengths and sum them\n    const lengthMatches = html.match(/Total Print Length:\\s*([\\d.]+)\\s*inches/gi);\n    if (lengthMatches) {\n      let totalLength = 0;\n      lengthMatches.forEach(match => {\n        const lenMatch = match.match(/([\\d.]+)/);\n        if (lenMatch) {\n          totalLength += parseFloat(lenMatch[1]);\n        }\n      });\n      result.totalPrintLength = totalLength.toString();\n    }\n    \n    // Extract gang sheet URLs\n    const gangSheetUrls = [];\n    const gangSheetMatches = html.match(/<a href=\"(https:\\/\\/www\\.jiffy\\.com\\/dtf_gang_sheets[^\"]+)\">/g);\n    if (gangSheetMatches) {\n      gangSheetMatches.forEach(match => {\n        const urlMatch = match.match(/href=\"([^\"]+)\"/);\n        if (urlMatch) {\n          gangSheetUrls.push(urlMatch[1]);\n        }\n      });\n    }\n    result.gangSheetUrls = gangSheetUrls;\n    \n    // Extract cutline references\n    const cutlineRefs = [];\n    const cutlineMatches = html.match(/<a href=\"(https:\\/\\/jiffy-transfers\\.imgix\\.net[^\"]+)\">/g);\n    if (cutlineMatches) {\n      cutlineMatches.forEach(match => {\n        const urlMatch = match.match(/href=\"([^\"]+)\"/);\n        if (urlMatch) {\n          const url = urlMatch[1];\n          // Extract filename from dl parameter\n          const dlMatch = url.match(/dl=([^&]+)/);\n          const filename = dlMatch ? decodeURIComponent(dlMatch[1]) : '';\n          \n          cutlineRefs.push({\n            url: url,\n            filename: filename || url.split('/').pop().split('?')[0],\n            type: 'cutline_reference'\n          });\n        }\n      });\n    }\n    result.cutlineReferences = cutlineRefs;\n    \n    return result;\n  };\n  \n  const parsedSections = parseSections(html);\n  \n  // Get all unique gang sheet URLs\n  const allGangSheetUrls = [...new Set([...fileInfo.links, ...parsedSections.gangSheetUrls])];\n  \n  // Get gang sheet files (non-reference files)\n  const gangSheetFiles = fileInfo.fileDetails.filter(f => f.type !== 'cutline_reference');\n  \n  // Get cutline references\n  const cutlineReferences = fileInfo.fileDetails.filter(f => f.type === 'cutline_reference');\n  \n  // Create output\n  const output = {\n    // HTML content\n    html: html,\n    html_original: email.html || '',\n    \n    // Order identifiers\n    orderId: orderId,\n    submissionId: submissionId,\n    source: 'jiffy',\n    poNumber: basicInfo.poNumber,\n    jiffyPoNumber: basicInfo.poNumber,\n    \n    // Order details\n    orderType: parsedSections.orderType || basicInfo.orderType,\n    rushService: rushService,\n    productTypes: [],\n    productTypesString: '',\n    \n    // Customer info\n    customer: {\n      email: 'orders@jiffy.com',\n      name: 'Jiffy',\n      company: 'Jiffy',\n      phone: '',\n      isB2B: true\n    },\n    \n    // Shipping info\n    shipping: shippingAddress,\n    shippingDate: basicInfo.shippingDate,\n    \n    // Financial\n    financial: totals,\n    paymentStatus: 'Paid',\n    \n    // Items (from parsed sections)\n    items: allItems,\n    itemCount: allItems.length,\n    \n    // Files and gang sheets\n    files: gangSheetFiles,\n    gangSheetUrls: allGangSheetUrls,\n    cutlineReferences: cutlineReferences,\n    \n    // File status\n    needsFile: allGangSheetUrls.length === 0,\n    fileStatus: allGangSheetUrls.length > 0 ? 'All Files Received' : 'Pending Files',\n    \n    // Shipping label\n    shipping_label_url: shippingLabelInfo?.url || null,\n    shipping_label_google_drive: shippingLabelInfo?.url || null,\n    shippingLabel: shippingLabelInfo,\n    \n    // Additional metadata\n    meta: {\n      jiffy: {\n        poNumber: basicInfo.poNumber,\n        orderType: parsedSections.orderType || basicInfo.orderType,\n        productTypes: [],\n        shippingLabel: shippingLabelInfo,\n        cutlineReferences: cutlineReferences,\n        totalPrintLength: parsedSections.totalPrintLength,\n        precutQuantity: parsedSections.precutQuantity,\n        shippingDate: basicInfo.shippingDate\n      }\n    },\n    \n    // Formatted text summary\n    formatted_text: `ORDER SUMMARY\n=============\nPO NUMBER: ${basicInfo.poNumber}\nORDER TYPE: ${parsedSections.orderType || basicInfo.orderType}\nQUALITY CHECK: ${html.includes('Requires Quality Check:') ? (html.includes('Yes') ? 'Yes' : 'No') : 'No'}\nSHIPPING DATE: ${basicInfo.shippingDate}\nDELIVERY ADDRESS:\n${shippingAddress ? `${shippingAddress.name}\n${shippingAddress.address1}\n${shippingAddress.city}, ${shippingAddress.state} ${shippingAddress.zip}` : 'N/A'}\n\nITEMS: ${allItems.length} total items\nPRODUCT TYPES: ${allItems.map(i => i.productType).filter((v, i, a) => a.indexOf(v) === i).join(', ')}\nSUBTOTAL: $${totals.subtotal.toFixed(2)}\nSHIPPING: $${totals.shipping.toFixed(2)}\nTOTAL: $${totals.total.toFixed(2)}\n\n${parsedSections.precutQuantity > 0 ? `PRE-CUT QUANTITY: ${parsedSections.precutQuantity}\\n` : ''}${parsedSections.totalPrintLength ? `TOTAL PRINT LENGTH: ${parsedSections.totalPrintLength} inches\\n` : ''}\n\nGANG SHEET FILES:\n${allGangSheetUrls.map(url => `- ${url}`).join('\\n')}\n\n${cutlineReferences.length > 0 ? `\nCUTLINE REFERENCES:\n${cutlineReferences.map(ref => `- ${ref.url}`).join('\\n')}` : ''}`\n  };\n  \n  return { json: output };\n});"
      },
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        -940,
        100
      ],
      "id": "5569e524-05a6-414b-a1a7-1d2f57ed1cbc",
      "name": "Format HTML",
      "onError": "continueRegularOutput"
    },
    {
      "parameters": {
        "inputDataFieldName": "=data0",
        "name": "={{ $binary.data0.fileName }}",
        "driveId": {
          "__rl": true,
          "mode": "list",
          "value": "My Drive"
        },
        "folderId": {
          "__rl": true,
          "value": "1qX3l4YNYppquctZFh9_FnJhf0FSjExaf",
          "mode": "list",
          "cachedResultName": "TRANSFER SUPERSTARS",
          "cachedResultUrl": "https://drive.google.com/drive/folders/1qX3l4YNYppquctZFh9_FnJhf0FSjExaf"
        },
        "options": {}
      },
      "type": "n8n-nodes-base.googleDrive",
      "typeVersion": 3,
      "position": [
        -1560,
        100
      ],
      "id": "f7dd5c1d-04bf-44d2-a9d2-d53f1fb24516",
      "name": "Google Drive",
      "credentials": {
        "googleDriveOAuth2Api": {
          "name": "<your credential>"
        }
      }
    },
    {
      "parameters": {
        "operation": "share",
        "fileId": {
          "__rl": true,
          "value": "={{ $json.id }}",
          "mode": "id"
        },
        "permissionsUi": {
          "permissionsValues": {
            "role": "reader",
            "type": "anyone"
          }
        },
        "options": {}
      },
      "type": "n8n-nodes-base.googleDrive",
      "typeVersion": 3,
      "position": [
        -1400,
        100
      ],
      "id": "76177056-064f-4cd4-a52a-92dae620a031",
      "name": "Google Drive Share File",
      "credentials": {
        "googleDriveOAuth2Api": {
          "name": "<your credential>"
        }
      }
    },
    {
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "loose",
            "version": 2
          },
          "conditions": [
            {
              "id": "d226ada2-5080-4c40-82b4-809bbf0037bf",
              "leftValue": "={{ $json.text }}",
              "rightValue": "Pre-Cut",
              "operator": {
                "type": "string",
                "operation": "contains"
              }
            },
            {
              "id": "40675e5c-5375-4c6c-8d14-5935c6b24956",
              "leftValue": "{{ $json.text }}",
              "rightValue": "Pre-cut",
              "operator": {
                "type": "string",
                "operation": "contains"
              }
            }
          ],
          "combinator": "or"
        },
        "looseTypeValidation": true,
        "options": {}
      },
      "type": "n8n-nodes-base.filter",
      "typeVersion": 2.2,
      "position": [
        -1700,
        100
      ],
      "id": "867ac6ca-2001-4366-8714-a6f3a56e24b4",
      "name": "Filter",
      "onError": "continueRegularOutput"
    },
    {
      "parameters": {
        "jsCode": "// Fix Item Count and add Precut Qty to Items\nconst items = $input.all();\n\nreturn items.map(item => {\n  const data = item.json;\n  \n  // Deep clone to avoid modifying original\n  const output = JSON.parse(JSON.stringify(data));\n  \n  // Fix the order data\n  if (output.order) {\n    // Parse Items Data JSON to get actual item count\n    let actualItemCount = 0;\n    if (data.items && Array.isArray(data.items)) {\n      actualItemCount = data.items.length;\n    }\n    \n    // Update the item count in summary\n    if (output.order.summary) {\n      output.order.summary.itemCount = actualItemCount;\n    }\n    \n    // Get precut quantity from order meta\n    let orderPrecutQty = 0;\n    if (output.order.meta?.jiffy?.precutQuantity !== undefined) {\n      orderPrecutQty = output.order.meta.jiffy.precutQuantity;\n    }\n    \n    // Fix items array - add precutQty to each item\n    if (output.items && Array.isArray(output.items)) {\n      output.items = output.items.map(orderItem => {\n        // Determine precut quantity for this item\n        let itemPrecutQty = 0;\n        \n        // Check if this item is precut\n        if (orderItem.isPrecut) {\n          // First check if item has its own precut quantity\n          if (orderItem.meta?.jiffy?.precutQuantity !== undefined) {\n            itemPrecutQty = orderItem.meta.jiffy.precutQuantity;\n          } \n          // Otherwise use order-level precut quantity\n          else if (orderPrecutQty > 0) {\n            itemPrecutQty = orderPrecutQty;\n          }\n          // If no precut quantity found but item is marked as precut, default to item qty\n          else {\n            itemPrecutQty = orderItem.qty || 1;\n          }\n        }\n        \n        // Return item with precutQty added\n        return {\n          ...orderItem,\n          precutQty: itemPrecutQty,\n          // Ensure qty is the line item quantity, not precut quantity\n          qty: orderItem.qty || 1\n        };\n      });\n    }\n  }\n  \n  return { json: output };\n});"
      },
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        220,
        -380
      ],
      "id": "4311c85d-0b5e-42bd-8c7d-556a69edfb90",
      "name": "Fix Item Counts",
      "onError": "continueErrorOutput"
    },
    {
      "parameters": {
        "jsCode": "// Process Shipping Label Attachment\n// This node should run after the Airtable - Upsert Order node\n\nconst items = $input.all();\nconst parsedData = $('Function - Parse Jiffy').all();\n\nreturn items.map((item, index) => {\n  const orderRecordId = item.json.id; // Airtable record ID from upsert\n  const orderData = parsedData[index]?.json?.order || {};\n  const attachmentData = orderData._attachments || {};\n  \n  // Skip if no shipping label URL\n  if (!attachmentData.shippingLabelUrl || !orderRecordId) {\n    return {\n      json: {\n        skip: true,\n        reason: !orderRecordId ? 'No order record ID' : 'No shipping label URL',\n        orderId: orderData.orderId,\n        orderRecordId: orderRecordId\n      }\n    };\n  }\n  \n  // Prepare attachment in Airtable format\n  const attachment = {\n    url: attachmentData.shippingLabelUrl,\n    filename: attachmentData.shippingLabelFilename || `JIFFY-${orderData.jiffyPoNumber || 'order'}-shipping-label.pdf`\n  };\n  \n  return {\n    json: {\n      recordId: orderRecordId,\n      attachments: [attachment],\n      orderId: orderData.orderId,\n      source: orderData.source,\n      debug: {\n        hasUrl: !!attachmentData.shippingLabelUrl,\n        filename: attachment.filename\n      }\n    }\n  };\n});"
      },
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        720,
        -420
      ],
      "id": "110dd548-60ff-4b00-b237-e7dbf31f6d1c",
      "name": "Process Shipping Label Attachment"
    },
    {
      "parameters": {
        "authentication": "airtableOAuth2Api",
        "operation": "update",
        "base": {
          "__rl": true,
          "value": "appZdp18sltDYOs4s",
          "mode": "list",
          "cachedResultName": "Order Management",
          "cachedResultUrl": "https://airtable.com/appZdp18sltDYOs4s"
        },
        "table": {
          "__rl": true,
          "value": "tbl2XIKxHAG7e9BFS",
          "mode": "list",
          "cachedResultName": "Orders",
          "cachedResultUrl": "https://airtable.com/appZdp18sltDYOs4s/tbl2XIKxHAG7e9BFS"
        },
        "columns": {
          "mappingMode": "defineBelow",
          "value": {
            "Rush Service": false,
            "Pre-cut?": false,
            "Needs File?": false,
            "Force Batch": false,
            "Gang Sheet Required": false,
            "Shipping Label": "={{ [{ \"url\": $json.attachments[0].url }] }}",
            "Subtotal": 0,
            "Shipping $": 0,
            "Tax $": 0,
            "Total $": 0,
            "Item Count": 0,
            "Shopify Order Number": 0,
            "Jiffy PO Number": 0,
            "Discount Amount": 0,
            "Record ID": "={{ $json.recordId }}"
          },
          "matchingColumns": [
            "Record ID"
          ],
          "schema": [
            {
              "id": "id",
              "displayName": "id",
              "required": false,
              "defaultMatch": true,
              "display": true,
              "type": "string",
              "readOnly": true,
              "removed": false
            },
            {
              "id": "Record ID",
              "displayName": "Record ID",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "string",
              "readOnly": true,
              "removed": false
            },
            {
              "id": "ID",
              "displayName": "ID",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "string",
              "readOnly": true,
              "removed": true
            },
            {
              "id": "Order ID",
              "displayName": "Order ID",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Submission ID",
              "displayName": "Submission ID",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Source",
              "displayName": "Source",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "options",
              "options": [
                {
                  "name": "Shopify",
                  "value": "Shopify"
                },
                {
                  "name": "JotForm",
                  "value": "JotForm"
                },
                {
                  "name": "Jiffy",
                  "value": "Jiffy"
                },
                {
                  "name": "Draft Order",
                  "value": "Draft Order"
                }
              ],
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Customer Profile",
              "displayName": "Customer Profile",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "array",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Order Date",
              "displayName": "Order Date",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "dateTime",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Order Status",
              "displayName": "Order Status",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "options",
              "options": [
                {
                  "name": "New",
                  "value": "New"
                },
                {
                  "name": "Pending",
                  "value": "Pending"
                },
                {
                  "name": "In Production",
                  "value": "In Production"
                },
                {
                  "name": "Printed",
                  "value": "Printed"
                },
                {
                  "name": "QC",
                  "value": "QC"
                }
              ],
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Payment Status",
              "displayName": "Payment Status",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "options",
              "options": [
                {
                  "name": "Needs Invoicing",
                  "value": "Needs Invoicing"
                },
                {
                  "name": "Pending Payment",
                  "value": "Pending Payment"
                },
                {
                  "name": "Paid",
                  "value": "Paid"
                }
              ],
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Fulfillment Option",
              "displayName": "Fulfillment Option",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "options",
              "options": [
                {
                  "name": "Ship",
                  "value": "Ship"
                },
                {
                  "name": "Will Call",
                  "value": "Will Call"
                }
              ],
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Shipping Option",
              "displayName": "Shipping Option",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "options",
              "options": [
                {
                  "name": "Ground",
                  "value": "Ground"
                },
                {
                  "name": "Express",
                  "value": "Express"
                },
                {
                  "name": "Overnight",
                  "value": "Overnight"
                },
                {
                  "name": "Will Call",
                  "value": "Will Call"
                }
              ],
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Production Option",
              "displayName": "Production Option",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "options",
              "options": [
                {
                  "name": "Standard 2-3 Days",
                  "value": "Standard 2-3 Days"
                },
                {
                  "name": "Rush 1-2 Days",
                  "value": "Rush 1-2 Days"
                },
                {
                  "name": "Super Rush 24 hrs",
                  "value": "Super Rush 24 hrs"
                }
              ],
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Rush Service",
              "displayName": "Rush Service",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "boolean",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Pre-cut?",
              "displayName": "Pre-cut?",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "boolean",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Shipping Label",
              "displayName": "Shipping Label",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "array",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Subtotal",
              "displayName": "Subtotal",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "number",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Shipping $",
              "displayName": "Shipping $",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "number",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Tax $",
              "displayName": "Tax $",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "number",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Total $",
              "displayName": "Total $",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "number",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Item Count",
              "displayName": "Item Count",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "number",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Needs File?",
              "displayName": "Needs File?",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "boolean",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Meta (JSON)",
              "displayName": "Meta (JSON)",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Items Data (JSON)",
              "displayName": "Items Data (JSON)",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Linked Order Items",
              "displayName": "Linked Order Items",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "array",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Linked Batch",
              "displayName": "Linked Batch",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "string",
              "readOnly": true,
              "removed": true
            },
            {
              "id": "Order Summary",
              "displayName": "Order Summary",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Next Action Suggestion",
              "displayName": "Next Action Suggestion",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Email",
              "displayName": "Email",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Phone",
              "displayName": "Phone",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Shopify Order Number",
              "displayName": "Shopify Order Number",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "number",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Jiffy PO Number",
              "displayName": "Jiffy PO Number",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "number",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Customer Name",
              "displayName": "Customer Name",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Customer Company",
              "displayName": "Customer Company",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Shipping Address",
              "displayName": "Shipping Address",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Billing Address",
              "displayName": "Billing Address",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Shipping Country",
              "displayName": "Shipping Country",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Shipping State",
              "displayName": "Shipping State",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Shipping Zip",
              "displayName": "Shipping Zip",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Order Tags",
              "displayName": "Order Tags",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Customer Notes",
              "displayName": "Customer Notes",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Internal Notes",
              "displayName": "Internal Notes",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Source URL",
              "displayName": "Source URL",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Product Types",
              "displayName": "Product Types",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "array",
              "options": [
                {
                  "name": "DTF Transfers",
                  "value": "DTF Transfers"
                },
                {
                  "name": "DTF Gang Sheet",
                  "value": "DTF Gang Sheet"
                },
                {
                  "name": "Pre-cut DTF",
                  "value": "Pre-cut DTF"
                },
                {
                  "name": "Pre-cut UV",
                  "value": "Pre-cut UV"
                },
                {
                  "name": "Pre-cut Sublimation",
                  "value": "Pre-cut Sublimation"
                },
                {
                  "name": "UV Stickers",
                  "value": "UV Stickers"
                },
                {
                  "name": "UV Gang Sheet",
                  "value": "UV Gang Sheet"
                },
                {
                  "name": "Sublimation",
                  "value": "Sublimation"
                },
                {
                  "name": "Sample Pack",
                  "value": "Sample Pack"
                },
                {
                  "name": "Sample Packs",
                  "value": "Sample Packs"
                },
                {
                  "name": "Heat Press",
                  "value": "Heat Press"
                },
                {
                  "name": "Alignment Tool",
                  "value": "Alignment Tool"
                },
                {
                  "name": "Accessories",
                  "value": "Accessories"
                },
                {
                  "name": "UV DTF",
                  "value": "UV DTF"
                }
              ],
              "readOnly": false,
              "removed": false
            },
            {
              "id": "File Status",
              "displayName": "File Status",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "options",
              "options": [
                {
                  "name": "All Files Received",
                  "value": "All Files Received"
                },
                {
                  "name": "Awaiting Files",
                  "value": "Awaiting Files"
                }
              ],
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Discount Amount",
              "displayName": "Discount Amount",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "number",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Payment Method",
              "displayName": "Payment Method",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Currency Code",
              "displayName": "Currency Code",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Created At",
              "displayName": "Created At",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "dateTime",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Updated At",
              "displayName": "Updated At",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "dateTime",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Paid At",
              "displayName": "Paid At",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "dateTime",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Fulfilled At",
              "displayName": "Fulfilled At",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "dateTime",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Priority Level",
              "displayName": "Priority Level",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "options",
              "options": [
                {
                  "name": "High",
                  "value": "High"
                },
                {
                  "name": "Normal",
                  "value": "Normal"
                }
              ],
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Force Batch",
              "displayName": "Force Batch",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "boolean",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "QC Status",
              "displayName": "QC Status",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "options",
              "options": [
                {
                  "name": "Not Started",
                  "value": "Not Started"
                },
                {
                  "name": "Passed",
                  "value": "Passed"
                }
              ],
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Sync Status",
              "displayName": "Sync Status",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "options",
              "options": [
                {
                  "name": "Success",
                  "value": "Success"
                },
                {
                  "name": "Failed",
                  "value": "Failed"
                }
              ],
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Last Synced",
              "displayName": "Last Synced",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "dateTime",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Sync Errors",
              "displayName": "Sync Errors",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Linked Production",
              "displayName": "Linked Production",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "array",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Linked Files",
              "displayName": "Linked Files",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Linked Shipment",
              "displayName": "Linked Shipment",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "array",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Has Batch",
              "displayName": "Has Batch",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "string",
              "readOnly": true,
              "removed": true
            },
            {
              "id": "Autonumber",
              "displayName": "Autonumber",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "string",
              "readOnly": true,
              "removed": true
            },
            {
              "id": "Gang Sheet Required",
              "displayName": "Gang Sheet Required",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "boolean",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Batches",
              "displayName": "Batches",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Batches 2",
              "displayName": "Batches 2",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Batches 3",
              "displayName": "Batches 3",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Batches 4",
              "displayName": "Batches 4",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "array",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Customers",
              "displayName": "Customers",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "array",
              "readOnly": false,
              "removed": false
            }
          ],
          "attemptToConvertTypes": false,
          "convertFieldsToString": false
        },
        "options": {}
      },
      "type": "n8n-nodes-base.airtable",
      "typeVersion": 2.1,
      "position": [
        960,
        -340
      ],
      "id": "cdd9d389-f036-4ecc-b572-a0f2e6c6fa64",
      "name": "Upload Shipping Label",
      "credentials": {
        "airtableOAuth2Api": {
          "name": "<your credential>"
        }
      }
    },
    {
      "parameters": {
        "authentication": "airtableOAuth2Api",
        "operation": "upsert",
        "base": {
          "__rl": true,
          "value": "appZdp18sltDYOs4s",
          "mode": "list",
          "cachedResultName": "Order Management",
          "cachedResultUrl": "https://airtable.com/appZdp18sltDYOs4s"
        },
        "table": {
          "__rl": true,
          "value": "tblTN1vUIpu6HHqEL",
          "mode": "list",
          "cachedResultName": "Order Items",
          "cachedResultUrl": "https://airtable.com/appZdp18sltDYOs4s/tblTN1vUIpu6HHqEL"
        },
        "columns": {
          "mappingMode": "defineBelow",
          "value": {
            "Item UID": "={{ $json.itemUid }}",
            "Product Type": "={{ $json[\"Product Type\"] }}",
            "Quantity": "={{ $json.Qty }}",
            "Dimensions (in)": "={{ \n  (() => {\n    const dim = ($json.dimensions || '').toString().trim();\n    \n    // Return empty for non-dimensional content\n    if (!dim || \n        dim.toLowerCase().includes('sample') || \n        dim.toLowerCase().includes('pack') ||\n        dim.toLowerCase().includes('transfer') ||\n        dim.toLowerCase().includes('clothing') ||\n        dim.toLowerCase().includes('|') ||\n        dim.toLowerCase().includes('dtf') ||\n        dim.toLowerCase().includes('uv') ||\n        dim.toLowerCase().includes('sticker')) {\n      return '';\n    }\n    \n    // Clean up any parenthetical content first\n    let cleanDim = dim.replace(/\\s*\\([^)]*\\)/g, '').trim();\n    \n    // Already formatted with 'x' (like \"22 x 100\", \"22x100\", \"22 X 100\")\n    if (cleanDim.toLowerCase().includes('x')) {\n      const parts = cleanDim.split(/\\s*[xX]\\s*/);\n      if (parts.length === 2 && parts[0].match(/^\\d+$/) && parts[1].match(/^\\d+$/)) {\n        return parts[0] + ' x ' + parts[1];\n      }\n      return cleanDim; // Return as-is if already has x but doesn't match expected format\n    }\n    \n    // Concatenated format (like \"22100\", \"12050\")\n    if (/^\\d{4,5}$/.test(cleanDim)) {\n      // For 4-5 digit numbers, split at position 2\n      const width = cleanDim.slice(0, 2);\n      const length = cleanDim.slice(2);\n      return width + ' x ' + length;\n    }\n    \n    // Handle 3-digit numbers (like \"224\" could be \"22 x 4\")\n    if (/^\\d{3}$/.test(cleanDim) && cleanDim.startsWith('22')) {\n      const width = cleanDim.slice(0, 2);\n      const length = cleanDim.slice(2);\n      return width + ' x ' + length;\n    }\n    \n    // Handle other specific patterns if needed\n    // Only return if it looks like dimensions (contains only numbers, spaces, and basic dimension chars)\n    if (/^[\\d\\s.,\"-]+$/.test(cleanDim) && cleanDim.length > 0) {\n      return cleanDim;\n    }\n    \n    // Return empty for anything else that doesn't look like dimensions\n    return '';\n  })()\n}}",
            "Needs File": "={{ $json[\"Needs File?\"] }}",
            "File URL": "={{ $json[\"File URL\"] }}",
            "Item Status": "New",
            "Meta (JSON)": "={{ $json[\"Meta (JSON)\"] }}",
            "Line Item ID": "={{ $json[\"Line Item ID\"] }}",
            "Product ID": "={{ $json[\"Product ID\"] }}",
            "Variant ID": "={{ $json[\"Variant ID\"] }}",
            "SKU": "={{ $json.SKU }}",
            "Title": "={{ $json.Title }}",
            "File Name": "={{ $json['File Name'] }}",
            "Original File URL": "={{ $json['Original File URL'] }}",
            "Preview URL": "={{ $json['Preview URL'] }}",
            "Is Precut": "={{ $json['Pre-cut?'] }}",
            "Is Gang Sheet": "={{ $json[\"Product Type\"]?.includes(\"Gang Sheet\") ? \"true\": \"false\" }}",
            "Fulfillable Quantity": "={{ $json[\"Fulfillable Quantity\"] }}",
            "Total Discount": "=",
            "Total Cost (formula)": 0,
            "Attachment": "={{ [{ \"url\": $json['File URL'] }] }}",
            "File Dimensions": "={{ $json['Original Dimensions'] }}",
            "Print Facility": "={{ $json[\"Order ID\"]?.includes(\"JIFFY\") ? \"CHICO\" : \"\" }}",
            "Printer Assignment": "={{ $json[\"Order ID\"]?.includes(\"JIFFY\") ? \"C2\": \"\" }}",
            "Artwork QC": "Pending",
            "Batch Print Status": "Not Printed",
            "Linked Order": "={{ $json.Order }}",
            "File DPI": 0,
            "Precut Qty": "={{ $json.precutQty || 0 }}",
            "Gang Sheet Length": "={{ $json[\"Product Type\"]?.includes(\"Gang Sheet\") ? $json.Height : \"\" }}",
            "Cutline References": "={{ \n  $json.cutlineAttachments && $json.cutlineAttachments.length > 0 \n    ? $json.cutlineAttachments.map(a => ({ url: a.url })) \n    : [] \n}}"
          },
          "matchingColumns": [
            "SKU"
          ],
          "schema": [
            {
              "id": "id",
              "displayName": "id",
              "required": false,
              "defaultMatch": true,
              "display": true,
              "type": "string",
              "readOnly": true
            },
            {
              "id": "Order Item ID",
              "displayName": "Order Item ID",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "string",
              "readOnly": true,
              "removed": false
            },
            {
              "id": "Record ID",
              "displayName": "Record ID",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "string",
              "readOnly": true,
              "removed": false
            },
            {
              "id": "Item UID",
              "displayName": "Item UID",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Product Type",
              "displayName": "Product Type",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "options",
              "options": [
                {
                  "name": "Sublimation Gang Sheet",
                  "value": "Sublimation Gang Sheet"
                },
                {
                  "name": "DTF Gang Sheet",
                  "value": "DTF Gang Sheet"
                },
                {
                  "name": "DTF Transfers",
                  "value": "DTF Transfers"
                },
                {
                  "name": "UV Gang Sheet",
                  "value": "UV Gang Sheet"
                },
                {
                  "name": "UV Stickers",
                  "value": "UV Stickers"
                },
                {
                  "name": "Sublimation",
                  "value": "Sublimation"
                },
                {
                  "name": "Pre-cut DTF",
                  "value": "Pre-cut DTF"
                },
                {
                  "name": "Pre-cut UV",
                  "value": "Pre-cut UV"
                },
                {
                  "name": "Pre-cut Sublimation",
                  "value": "Pre-cut Sublimation"
                },
                {
                  "name": "Sample Pack",
                  "value": "Sample Pack"
                },
                {
                  "name": "Alignment Tool",
                  "value": "Alignment Tool"
                },
                {
                  "name": "Heat Press",
                  "value": "Heat Press"
                },
                {
                  "name": "Accessories",
                  "value": "Accessories"
                }
              ],
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Quantity",
              "displayName": "Quantity",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "number",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Unit Price",
              "displayName": "Unit Price",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "number",
              "readOnly": false,
              "removed": true
            },
            {
              "id": "Dimensions (in)",
              "displayName": "Dimensions (in)",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Needs File",
              "displayName": "Needs File",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "boolean",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "File URL",
              "displayName": "File URL",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Attachment",
              "displayName": "Attachment",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "array",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Item Status",
              "displayName": "Item Status",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "options",
              "options": [
                {
                  "name": "New",
                  "value": "New"
                },
                {
                  "name": "Pending Art",
                  "value": "Pending Art"
                },
                {
                  "name": "Art Received",
                  "value": "Art Received"
                },
                {
                  "name": "Ready for Production",
                  "value": "Ready for Production"
                },
                {
                  "name": "In Production",
                  "value": "In Production"
                },
                {
                  "name": "Quality Check",
                  "value": "Quality Check"
                },
                {
                  "name": "Ready to Ship",
                  "value": "Ready to Ship"
                },
                {
                  "name": "Ready for Pickup",
                  "value": "Ready for Pickup"
                },
                {
                  "name": "Shipped",
                  "value": "Shipped"
                },
                {
                  "name": "Picked Up",
                  "value": "Picked Up"
                }
              ],
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Print Facility",
              "displayName": "Print Facility",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "options",
              "options": [
                {
                  "name": "CHICO",
                  "value": "CHICO"
                },
                {
                  "name": "OUTPOST",
                  "value": "OUTPOST"
                }
              ],
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Printer Assignment",
              "displayName": "Printer Assignment",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "options",
              "options": [
                {
                  "name": "C2",
                  "value": "C2"
                },
                {
                  "name": "D2",
                  "value": "D2"
                },
                {
                  "name": "U2",
                  "value": "U2"
                },
                {
                  "name": "S2",
                  "value": "S2"
                },
                {
                  "name": "D6",
                  "value": "D6"
                }
              ],
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Meta (JSON)",
              "displayName": "Meta (JSON)",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Artwork QC",
              "displayName": "Artwork QC",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "options",
              "options": [
                {
                  "name": "Pending",
                  "value": "Pending"
                },
                {
                  "name": "Approved",
                  "value": "Approved"
                },
                {
                  "name": "Rejected",
                  "value": "Rejected"
                }
              ],
              "readOnly": false,
              "removed": false
            },
            {
              "id": "QC Notes",
              "displayName": "QC Notes",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "QC Improvement Suggestions",
              "displayName": "QC Improvement Suggestions",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Total Cost (formula)",
              "displayName": "Total Cost (formula)",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "number",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Batch Print Status",
              "displayName": "Batch Print Status",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "options",
              "options": [
                {
                  "name": "Not Printed",
                  "value": "Not Printed"
                },
                {
                  "name": "Queued",
                  "value": "Queued"
                },
                {
                  "name": "Printed",
                  "value": "Printed"
                }
              ],
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Ready for Batch",
              "displayName": "Ready for Batch",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "string",
              "readOnly": true,
              "removed": false
            },
            {
              "id": "Production Location",
              "displayName": "Production Location",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "string",
              "readOnly": true,
              "removed": false
            },
            {
              "id": "Line Item ID",
              "displayName": "Line Item ID",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Product ID",
              "displayName": "Product ID",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Variant ID",
              "displayName": "Variant ID",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "SKU",
              "displayName": "SKU",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Title",
              "displayName": "Title",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "File Name",
              "displayName": "File Name",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Original File URL",
              "displayName": "Original File URL",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "File DPI",
              "displayName": "File DPI",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "number",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "File Dimensions",
              "displayName": "File Dimensions",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Is Precut",
              "displayName": "Is Precut",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "boolean",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Precut Qty",
              "displayName": "Precut Qty",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "number",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Cutline References",
              "displayName": "Cutline References",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "array",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Is Gang Sheet",
              "displayName": "Is Gang Sheet",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "boolean",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Gang Sheet Length",
              "displayName": "Gang Sheet Length",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "number",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Requires Shipping",
              "displayName": "Requires Shipping",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "boolean",
              "readOnly": false,
              "removed": true
            },
            {
              "id": "Fulfillable Quantity",
              "displayName": "Fulfillable Quantity",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "number",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Linked Order",
              "displayName": "Linked Order",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "array",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Rush Service",
              "displayName": "Rush Service",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "string",
              "readOnly": true,
              "removed": false
            },
            {
              "id": "Order ID",
              "displayName": "Order ID",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "string",
              "readOnly": true,
              "removed": false
            },
            {
              "id": "Linked Files",
              "displayName": "Linked Files",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "array",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Linked Shipment",
              "displayName": "Linked Shipment",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "array",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Linked Production",
              "displayName": "Linked Production",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "array",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Batch ID",
              "displayName": "Batch ID",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "array",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Batch Name",
              "displayName": "Batch Name",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "string",
              "readOnly": true,
              "removed": false
            },
            {
              "id": "Has Batch",
              "displayName": "Has Batch",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "string",
              "readOnly": true,
              "removed": false
            },
            {
              "id": "Autonumber",
              "displayName": "Autonumber",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "string",
              "readOnly": true,
              "removed": false
            },
            {
              "id": "COGS",
              "displayName": "COGS",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "number",
              "readOnly": false,
              "removed": true
            },
            {
              "id": "Overall QC Status",
              "displayName": "Overall QC Status",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Processed File URL",
              "displayName": "Processed File URL",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": true
            },
            {
              "id": "Preview URL",
              "displayName": "Preview URL",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "File Color Mode",
              "displayName": "File Color Mode",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "options",
              "options": [
                {
                  "name": "RGB",
                  "value": "RGB"
                },
                {
                  "name": "",
                  "value": ""
                }
              ],
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Compare At Price",
              "displayName": "Compare At Price",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "number",
              "readOnly": false,
              "removed": true
            },
            {
              "id": "Total Discount",
              "displayName": "Total Discount",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "number",
              "readOnly": false,
              "removed": false
            }
          ]
        },
        "options": {
          "typecast": true
        }
      },
      "id": "d85a2024-1a86-452e-bfb6-6ea6be77f184",
      "name": "Upsert Order Items",
      "type": "n8n-nodes-base.airtable",
      "typeVersion": 2,
      "position": [
        1220,
        -320
      ],
      "credentials": {
        "airtableOAuth2Api": {
          "name": "<your credential>"
        }
      },
      "onError": "continueRegularOutput"
    },
    {
      "parameters": {
        "authentication": "airtableOAuth2Api",
        "operation": "upsert",
        "base": {
          "__rl": true,
          "value": "appZdp18sltDYOs4s",
          "mode": "list",
          "cachedResultName": "Order Management",
          "cachedResultUrl": "https://airtable.com/appZdp18sltDYOs4s"
        },
        "table": {
          "__rl": true,
          "value": "tbl2XIKxHAG7e9BFS",
          "mode": "list",
          "cachedResultName": "Orders",
          "cachedResultUrl": "https://airtable.com/appZdp18sltDYOs4s/tbl2XIKxHAG7e9BFS"
        },
        "columns": {
          "mappingMode": "defineBelow",
          "value": {
            "Order ID": "={{ $json.order.orderId }}",
            "Submission ID": "={{ $json.order.submissionId }}",
            "Source": "={{ $json.order.source.toTitleCase() }}",
            "Order Date": "={{ $json.order.orderDate || new Date().toISOString() }}",
            "Created At": "={{ $json.order.createdAt || new Date().toISOString() }}",
            "Updated At": "={{ $json.order.updatedAt || new Date().toISOString() }}",
            "Payment Status": "={{ $json.order.financial.paymentStatus || 'Paid' }}",
            "Order Status": "={{ $json.order.status.orderStatus }}",
            "Email": "={{ $json.order.source === 'jiffy' ? '' : ($json.order.customer?.email || '') }}",
            "Phone": "={{ (() => {\n  const phone = $json.order.customer.phone;\n  if (!phone) return '';\n  const cleaned = phone.toString().replace(/[^0-9]/g, '');\n  if (cleaned.length === 10) {\n    return cleaned.replace(/(\\d{3})(\\d{3})(\\d{4})/, '($1) $2-$3');\n  } else if (cleaned.length === 11 && cleaned[0] === '1') {\n    return cleaned.slice(1).replace(/(\\d{3})(\\d{3})(\\d{4})/, '($1) $2-$3');\n  } else {\n    return phone;\n  }\n})() }}",
            "Customer Name": "={{ $json.order.source === 'jiffy' ? $json.order.shipping.name.toTitleCase() : $json.order.customer.name.toTitleCase() }}",
            "Customer Company": "={{ $json.order.customer.company.toTitleCase() }}",
            "Shipping Address": "={{ $json.order.shipping.fullAddress.toTitleCase() || $json.order.billing.fullAddress.toTitleCase() }}",
            "Shipping Country": "={{ $json.order.shipping.country || 'US' }}",
            "Shipping State": "={{ $json.order.shipping.state || $json.order.billing.province }}",
            "Shipping Zip": "={{ $json.order.shipping.zip || $json.order.billing.zip }}",
            "Pre-cut?": "={{ $json.order.options?.precut === true }}",
            "Gang Sheet Required": "=false",
            "Subtotal": "={{ $json.order.financial.subtotal }}",
            "Shipping $": "={{ $json.order.financial.shipping }}",
            "Tax $": "={{ $json.order.financial.tax }}",
            "Total $": "={{ $json.order.financial.total }}",
            "Item Count": "={{ $json.order.summary.itemCount }}",
            "Needs File?": "={{ $json.order.options.needsFile }}",
            "File Status": "={{ $json.order.options.fileStatus }}",
            "Product Types": "={{ $json.order.options.productTypes.split(', ') }}",
            "Priority Level": "={{ $json.order.options.priorityLevel }}",
            "Order Tags": "={{ $json.order.options?.tags ? $json.order.options.tags.split(',').map(tag => tag.trim()).join(', ') : '' }}",
            "Customer Notes": "={{ $json.order.options.customerNotes || '' }}",
            "Meta (JSON)": "={{ JSON.stringify($json.order.meta) }}",
            "Jiffy PO Number": "={{ $json.order.meta?.jiffy?.poNumber || '' }}",
            "QC Status": "={{ $json.order.status.qcStatus || 'Not Started' }}",
            "Internal Notes": "={{ $json.order.options.internalNotes || '' }}",
            "Paid At": "={{ $json.order.paidAt || new Date().toISOString() }}",
            "Order Summary": "={{ $json.order.options.orderSummary }}",
            "Rush Service": "={{ $json.order.options.rushService === true ? true : false }}",
            "Force Batch": true,
            "Shopify Order Number": "={{ $json.order.meta?.shopify?.orderNumber || '' }}",
            "Fulfillment Option": "={{ $json.order.options.fulfillmentOption }}",
            "Shipping Option": "={{ $json.order.options.shippingOption }}",
            "Production Option": "={{ $json.order.options.productionOption }}",
            "Items Data (JSON)": "={{ JSON.stringify($json.items) }}",
            "Discount Amount": 0,
            "Billing Address": "={{ $json.order.billing.fullAddress }}",
            "Payment Method": "={{ $json.order.financial.paymentMethod || '' }}",
            "Committed Shipping Date": "={{ $json.order.meta.jiffy.rawData.meta.jiffy.shippingDate }}"
          },
          "matchingColumns": [
            "Order ID"
          ],
          "schema": [
            {
              "id": "id",
              "displayName": "id",
              "required": false,
              "defaultMatch": true,
              "display": true,
              "type": "string",
              "readOnly": true,
              "removed": false
            },
            {
              "id": "Record ID",
              "displayName": "Record ID",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "string",
              "readOnly": true,
              "removed": false
            },
            {
              "id": "ID",
              "displayName": "ID",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "string",
              "readOnly": true,
              "removed": false
            },
            {
              "id": "Order ID",
              "displayName": "Order ID",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Submission ID",
              "displayName": "Submission ID",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Source",
              "displayName": "Source",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "options",
              "options": [
                {
                  "name": "Shopify",
                  "value": "Shopify"
                },
                {
                  "name": "JotForm",
                  "value": "JotForm"
                },
                {
                  "name": "Jiffy",
                  "value": "Jiffy"
                },
                {
                  "name": "Draft Order",
                  "value": "Draft Order"
                }
              ],
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Customer Profile",
              "displayName": "Customer Profile",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "array",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Order Date",
              "displayName": "Order Date",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "dateTime",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Order Status",
              "displayName": "Order Status",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "options",
              "options": [
                {
                  "name": "New",
                  "value": "New"
                },
                {
                  "name": "In Review",
                  "value": "In Review"
                },
                {
                  "name": "Pre-Production",
                  "value": "Pre-Production"
                },
                {
                  "name": "In Production",
                  "value": "In Production"
                },
                {
                  "name": "Print Complete",
                  "value": "Print Complete"
                },
                {
                  "name": "Quality Check",
                  "value": "Quality Check"
                },
                {
                  "name": "Ready to Fulfill",
                  "value": "Ready to Fulfill"
                },
                {
                  "name": "Fulfilled",
                  "value": "Fulfilled"
                },
                {
                  "name": "Delivered",
                  "value": "Delivered"
                },
                {
                  "name": "Closed",
                  "value": "Closed"
                },
                {
                  "name": "On Hold",
                  "value": "On Hold"
                },
                {
                  "name": "Cancelled",
                  "value": "Cancelled"
                },
                {
                  "name": "Refund Processing",
                  "value": "Refund Processing"
                }
              ],
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Status Changed At",
              "displayName": "Status Changed At",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "string",
              "readOnly": true,
              "removed": false
            },
            {
              "id": "Hours in Status",
              "displayName": "Hours in Status",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "string",
              "readOnly": true,
              "removed": false
            },
            {
              "id": "Stage Progress",
              "displayName": "Stage Progress",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "string",
              "readOnly": true,
              "removed": false
            },
            {
              "id": "Production Progress",
              "displayName": "Production Progress",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "string",
              "readOnly": true,
              "removed": false
            },
            {
              "id": "\ud83d\udea8 Alert Status",
              "displayName": "\ud83d\udea8 Alert Status",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "string",
              "readOnly": true,
              "removed": false
            },
            {
              "id": "Payment Status",
              "displayName": "Payment Status",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "options",
              "options": [
                {
                  "name": "Needs Invoicing",
                  "value": "Needs Invoicing"
                },
                {
                  "name": "Pending Payment",
                  "value": "Pending Payment"
                },
                {
                  "name": "Paid",
                  "value": "Paid"
                }
              ],
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Fulfillment Option",
              "displayName": "Fulfillment Option",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "options",
              "options": [
                {
                  "name": "Ship",
                  "value": "Ship"
                },
                {
                  "name": "Will Call",
                  "value": "Will Call"
                },
                {
                  "name": "Local Pickup",
                  "value": "Local Pickup"
                },
                {
                  "name": "Digital Delivery",
                  "value": "Digital Delivery"
                }
              ],
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Shipping Option",
              "displayName": "Shipping Option",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "options",
              "options": [
                {
                  "name": "Ground",
                  "value": "Ground"
                },
                {
                  "name": "Express",
                  "value": "Express"
                },
                {
                  "name": "Overnight",
                  "value": "Overnight"
                },
                {
                  "name": "Will Call",
                  "value": "Will Call"
                }
              ],
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Production Option",
              "displayName": "Production Option",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "options",
              "options": [
                {
                  "name": "Standard 2-3 Days",
                  "value": "Standard 2-3 Days"
                },
                {
                  "name": "Rush 1-2 Days",
                  "value": "Rush 1-2 Days"
                },
                {
                  "name": "Super Rush 24 hrs",
                  "value": "Super Rush 24 hrs"
                }
              ],
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Committed Shipping Date",
              "displayName": "Committed Shipping Date",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "dateTime",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Rush Service",
              "displayName": "Rush Service",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "boolean",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Pre-cut?",
              "displayName": "Pre-cut?",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "boolean",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Shipping Label",
              "displayName": "Shipping Label",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "array",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Subtotal",
              "displayName": "Subtotal",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "number",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Shipping $",
              "displayName": "Shipping $",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "number",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Tax $",
              "displayName": "Tax $",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "number",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Total $",
              "displayName": "Total $",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "number",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Item Count",
              "displayName": "Item Count",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "number",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Needs File?",
              "displayName": "Needs File?",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "boolean",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Meta (JSON)",
              "displayName": "Meta (JSON)",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Items Data (JSON)",
              "displayName": "Items Data (JSON)",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Linked Order Items",
              "displayName": "Linked Order Items",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "array",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Linked Batch",
              "displayName": "Linked Batch",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "string",
              "readOnly": true,
              "removed": false
            },
            {
              "id": "Order Summary",
              "displayName": "Order Summary",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Email",
              "displayName": "Email",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Phone",
              "displayName": "Phone",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Shopify Order Number",
              "displayName": "Shopify Order Number",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "number",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Jiffy PO Number",
              "displayName": "Jiffy PO Number",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "number",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Customer Name",
              "displayName": "Customer Name",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Customer Company",
              "displayName": "Customer Company",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Shipping Address",
              "displayName": "Shipping Address",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Billing Address",
              "displayName": "Billing Address",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Shipping Country",
              "displayName": "Shipping Country",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Shipping State",
              "displayName": "Shipping State",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Shipping Zip",
              "displayName": "Shipping Zip",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Order Tags",
              "displayName": "Order Tags",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Customer Notes",
              "displayName": "Customer Notes",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Internal Notes",
              "displayName": "Internal Notes",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Source URL",
              "displayName": "Source URL",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": true
            },
            {
              "id": "Product Types",
              "displayName": "Product Types",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "array",
              "options": [
                {
                  "name": "DTF Transfers",
                  "value": "DTF Transfers"
                },
                {
                  "name": "DTF Gang Sheet",
                  "value": "DTF Gang Sheet"
                },
                {
                  "name": "Pre-cut DTF",
                  "value": "Pre-cut DTF"
                },
                {
                  "name": "Pre-cut UV",
                  "value": "Pre-cut UV"
                },
                {
                  "name": "Pre-cut Sublimation",
                  "value": "Pre-cut Sublimation"
                },
                {
                  "name": "UV Stickers",
                  "value": "UV Stickers"
                },
                {
                  "name": "UV Gang Sheet",
                  "value": "UV Gang Sheet"
                },
                {
                  "name": "Sublimation",
                  "value": "Sublimation"
                },
                {
                  "name": "Sample Pack",
                  "value": "Sample Pack"
                },
                {
                  "name": "Sample Packs",
                  "value": "Sample Packs"
                },
                {
                  "name": "Heat Press",
                  "value": "Heat Press"
                },
                {
                  "name": "Alignment Tool",
                  "value": "Alignment Tool"
                },
                {
                  "name": "Accessories",
                  "value": "Accessories"
                },
                {
                  "name": "UV DTF",
                  "value": "UV DTF"
                }
              ],
              "readOnly": false,
              "removed": false
            },
            {
              "id": "File Status",
              "displayName": "File Status",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "options",
              "options": [
                {
                  "name": "All Files Received",
                  "value": "All Files Received"
                },
                {
                  "name": "Awaiting Files",
                  "value": "Awaiting Files"
                }
              ],
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Discount Amount",
              "displayName": "Discount Amount",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "number",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Payment Method",
              "displayName": "Payment Method",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Created At",
              "displayName": "Created At",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "dateTime",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Updated At",
              "displayName": "Updated At",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "dateTime",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Paid At",
              "displayName": "Paid At",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "dateTime",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Fulfilled At",
              "displayName": "Fulfilled At",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "dateTime",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Priority Level",
              "displayName": "Priority Level",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "options",
              "options": [
                {
                  "name": "High",
                  "value": "High"
                },
                {
                  "name": "Normal",
                  "value": "Normal"
                }
              ],
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Force Batch",
              "displayName": "Force Batch",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "boolean",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "QC Status",
              "displayName": "QC Status",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "options",
              "options": [
                {
                  "name": "Not Started",
                  "value": "Not Started"
                },
                {
                  "name": "Passed",
                  "value": "Passed"
                }
              ],
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Stuck Orders Alert",
              "displayName": "Stuck Orders Alert",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "string",
              "readOnly": true,
              "removed": false
            },
            {
              "id": "Linked Production",
              "displayName": "Linked Production",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "array",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Linked Files",
              "displayName": "Linked Files",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Linked Shipment",
              "displayName": "Linked Shipment",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "array",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Has Batch",
              "displayName": "Has Batch",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "string",
              "readOnly": true,
              "removed": false
            },
            {
              "id": "Autonumber",
              "displayName": "Autonumber",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "string",
              "readOnly": true,
              "removed": false
            },
            {
              "id": "Gang Sheet Required",
              "displayName": "Gang Sheet Required",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "boolean",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Batches",
              "displayName": "Batches",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Batches 2",
              "displayName": "Batches 2",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Batches 3",
              "displayName": "Batches 3",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Batches 4",
              "displayName": "Batches 4",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "array",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Customers",
              "displayName": "Customers",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "array",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Invoices",
              "displayName": "Invoices",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "array",
              "readOnly": false,
              "removed": false
            }
          ],
          "typecast": true
        },
        "options": {}
      },
      "id": "45fafe9d-38f2-41c4-8f3e-0d05b9770eeb",
      "name": "Upsert Orders",
      "type": "n8n-nodes-base.airtable",
      "typeVersion": 2,
      "position": [
        480,
        -400
      ],
      "executeOnce": false,
      "credentials": {
        "airtableOAuth2Api": {
          "name": "<your credential>"
        }
      },
      "onError": "continueErrorOutput"
    },
    {
      "parameters": {
        "authentication": "airtableOAuth2Api",
        "operation": "upsert",
        "base": {
          "__rl": true,
          "value": "appZdp18sltDYOs4s",
          "mode": "list",
          "cachedResultName": "Order Management",
          "cachedResultUrl": "https://airtable.com/appZdp18sltDYOs4s"
        },
        "table": {
          "__rl": true,
          "value": "tblcrpW5ls1cCEN5c",
          "mode": "list",
          "cachedResultName": "Customers",
          "cachedResultUrl": "https://airtable.com/appZdp18sltDYOs4s/tblcrpW5ls1cCEN5c"
        },
        "columns": {
          "mappingMode": "defineBelow",
          "value": {
            "Email": "={{ $json.fields?.Email?.toLowerCase() || '' }}",
            "First Name": "={{ $json.fields?.['Customer Name']?.split(' ')[0].toTitleCase() || '' }}",
            "Last Name": "={{ $json.fields?.['Customer Name']?.split(' ').slice(1).join(' ').toTitleCase() || '' }}",
            "Phone Number": "={{ $json.fields?.Phone || '' }}",
            "Company": "={{ $json.fields?.['Customer Company'].toTitleCase() || '' }}",
            "Street": "={{ $json.fields?.['Billing Address']?.split(',')[0]?.trim().toTitleCase() || $json.fields?.['Shipping Address']?.split(',')[0]?.trim() || '' }}",
            "City": "={{ $json.fields?.['Billing Address']?.split(',')[1]?.trim().toTitleCase() || $json.fields?.['Shipping Address']?.split(',')[1]?.trim() || '' }}",
            "State": "={{ $json.fields?.['Billing Address']?.match(/,\\s*([A-Z]{2})\\s+\\d{5}/)?.[1].toUpperCase() || $json.fields?.['Shipping State'] || '' }}",
            "Zip": "={{ (() => { try { return JSON.parse($json.fields?.['Meta (JSON)'] || '{}').shopify?.billing_address?.zip || ''; } catch(e) { return ''; } })() }}",
            "Country": "={{ $json.fields?.['Shipping Country'] || 'United States' }}",
            "Full Address": "={{ $json.fields?.['Billing Address']?.split(',')[0]?.trim().toTitleCase() || $json.fields?.['Shipping Address']?.split(',')[0]?.trim().toTitleCase() || '' }}\n{{ $json.fields?.['Billing Address']?.split(',')[1]?.trim().toTitleCase() || $json.fields?.['Shipping Address']?.split(',')[1]?.trim().toTitleCase() || '' }}, {{ $json.fields?.['Billing Address']?.match(/,\\s*([A-Z]{2})\\s+\\d{5}/)?.[1].toTitleCase() || $json.fields?.['Shipping State'] || '' }}\n",
            "Email Opt-in": "={{ true }}",
            "SMS Opt-in": "={{ false }}",
            "Tax Exempt": "={{ $json.fields?.['Tax $'] === 0 || $json.fields?.['Payment Status'] === 'Paid' && !$json.fields?.['Tax $'] }}",
            "Verified Email": "={{ true }}",
            "Source": "={{ [$json.fields?.Source || 'Shopify'] }}",
            "Meta (JSON)": "={{ JSON.stringify({ source: $json.order?.source || 'Shopify', orderId: $json.order?.orderId, submissionId: $json.fields?.['Submission ID'], created: new Date().toISOString() }) }}",
            "Customer Since": "={{ $json.fields?.['Created At'] || new Date().toISOString() }}",
            "Last Order Date": "={{ $json.fields?.['Order Date'] || $json.fields?.['Created At'] }}",
            "Preferred Products": "={{ $json.fields?.['Product Types'] ? $json.fields['Product Types'].filter(type => ['DTF Transfers', 'Gang Sheet', 'Pre-cut'].includes(type)) : [] }}",
            "Address": "={{ $json.fields['Shipping Address'] }}",
            "Orders": "={{ [$json.id] }}",
            "Items Data (JSON)": "={{ $json.fields[\"Items Data (JSON)\"] }}"
          },
          "matchingColumns": [
            "Email"
          ],
          "schema": [
            {
              "id": "id",
              "displayName": "id",
              "required": false,
              "defaultMatch": true,
              "display": true,
              "type": "string",
              "readOnly": true,
              "removed": false
            },
            {
              "id": "ID",
              "displayName": "ID",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "string",
              "readOnly": true,
              "removed": true
            },
            {
              "id": "Email",
              "displayName": "Email",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "First Name",
              "displayName": "First Name",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Last Name",
              "displayName": "Last Name",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Phone Number",
              "displayName": "Phone Number",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Address",
              "displayName": "Address",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Company",
              "displayName": "Company",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Role",
              "displayName": "Role",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Orders",
              "displayName": "Orders",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "array",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Full Name",
              "displayName": "Full Name",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "string",
              "readOnly": true,
              "removed": false
            },
            {
              "id": "Average Order Value",
              "displayName": "Average Order Value",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "string",
              "readOnly": true,
              "removed": false
            },
            {
              "id": "Order Summary",
              "displayName": "Order Summary",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": true
            },
            {
              "id": "Street",
              "displayName": "Street",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "City",
              "displayName": "City",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "State",
              "displayName": "State",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Zip",
              "displayName": "Zip",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Country",
              "displayName": "Country",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Email Opt-in",
              "displayName": "Email Opt-in",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "boolean",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "SMS Opt-in",
              "displayName": "SMS Opt-in",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "boolean",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Tags",
              "displayName": "Tags",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "array",
              "options": [
                {
                  "name": "wholesale",
                  "value": "wholesale"
                },
                {
                  "name": "repeat-customer",
                  "value": "repeat-customer"
                },
                {
                  "name": "vip",
                  "value": "vip"
                },
                {
                  "name": "new-customer",
                  "value": "new-customer"
                },
                {
                  "name": "high-volume",
                  "value": "high-volume"
                },
                {
                  "name": "partner",
                  "value": "partner"
                }
              ],
              "readOnly": false,
              "removed": true
            },
            {
              "id": "Meta (JSON)",
              "displayName": "Meta (JSON)",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Items Data (JSON)",
              "displayName": "Items Data (JSON)",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Full Address",
              "displayName": "Full Address",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Tax Exempt",
              "displayName": "Tax Exempt",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "boolean",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Verified Email",
              "displayName": "Verified Email",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "boolean",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Accepts Marketing Updated",
              "displayName": "Accepts Marketing Updated",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "dateTime",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Customer Since",
              "displayName": "Customer Since",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "dateTime",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Last Order Date",
              "displayName": "Last Order Date",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "dateTime",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Order Frequency",
              "displayName": "Order Frequency",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Preferred Products",
              "displayName": "Preferred Products",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "array",
              "options": [
                {
                  "name": "DTF Transfers",
                  "value": "DTF Transfers"
                },
                {
                  "name": "Gang Sheet",
                  "value": "Gang Sheet"
                },
                {
                  "name": "Pre-cut",
                  "value": "Pre-cut"
                },
                {
                  "name": "UV Stickers",
                  "value": "UV Stickers"
                },
                {
                  "name": "Sublimation",
                  "value": "Sublimation"
                },
                {
                  "name": "UV DTF",
                  "value": "UV DTF"
                },
                {
                  "name": "Pre-cut DTF",
                  "value": "Pre-cut DTF"
                },
                {
                  "name": "Pre-cut UV",
                  "value": "Pre-cut UV"
                },
                {
                  "name": "Pre-cut Sublimation",
                  "value": "Pre-cut Sublimation"
                }
              ],
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Risk Level",
              "displayName": "Risk Level",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "options",
              "options": [
                {
                  "name": "Low",
                  "value": "Low"
                }
              ],
              "readOnly": false,
              "removed": true
            },
            {
              "id": "Source",
              "displayName": "Source",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "array",
              "options": [
                {
                  "name": "Shopify",
                  "value": "Shopify"
                },
                {
                  "name": "Email",
                  "value": "Email"
                },
                {
                  "name": "JotForm",
                  "value": "JotForm"
                },
                {
                  "name": "Jiffy",
                  "value": "Jiffy"
                }
              ],
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Browser IP",
              "displayName": "Browser IP",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Referral Source",
              "displayName": "Referral Source",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Record ID",
              "displayName": "Record ID",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "string",
              "readOnly": true,
              "removed": false
            },
            {
              "id": "Autonumber",
              "displayName": "Autonumber",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "string",
              "readOnly": true,
              "removed": false
            },
            {
              "id": "Orders 2",
              "displayName": "Orders 2",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "array",
              "readOnly": false,
              "removed": true
            }
          ],
          "typecast": true
        },
        "options": {}
      },
      "id": "39b41cb9-ae58-48a3-b67c-b08b29eaddee",
      "name": "Upsert Customers",
      "type": "n8n-nodes-base.airtable",
      "typeVersion": 2,
      "position": [
        960,
        -560
      ],
      "credentials": {
        "airtableOAuth2Api": {
          "name": "<your credential>"
        }
      },
      "onError": "continueErrorOutput"
    },
    {
      "parameters": {
        "content": "## \ud83d\udce5 ORDER SOURCES\n\n**1. Shopify Orders**\n- API: `/admin/api/2023-10/orders.json`\n- Fetches last 2 days\n- Converts to TS-TSS#### format\n- Detects rush/precut tags\n\n**2. Gmail/Jiffy Orders**\n- B2B Dropship orders\n- Order ID: JIFFY-{timestamp}\n- Includes shipping labels\n- Tracks gang sheets & cutlines\n\n**3. JotForm Submissions**\n- Custom order forms\n- Direct customer input\n- Parsed from form answers",
        "height": 980,
        "width": 1830,
        "color": 5
      },
      "id": "4ebbcf1f-80b9-4ab8-8de9-6d1f9d9b7408",
      "name": "\ud83d\udce8 Order Sources",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        -1920,
        -540
      ]
    },
    {
      "parameters": {
        "content": "## \ud83c\udfa8 FILE PROCESSING\n\n**File Validation Checks:**\n- Valid URL format\n- Accessibility test\n- File type verification\n- Color mode detection (RGB/CMYK)\n\n**Cutline Handling:**\n- Matches cutline references\n- Links to Google Drive\n- Attaches to order items\n\n**Gang Sheet Detection:**\n- Identifies gang sheet products\n- Extracts gang sheet URLs\n- Creates special batches",
        "height": 420,
        "width": 1030,
        "color": 6
      },
      "id": "d0e7c2b0-8766-4c89-8e36-e0e7d357c637",
      "name": "\ud83c\udfa8 File Processing",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        1640,
        -360
      ]
    },
    {
      "parameters": {
        "content": "## \u26a0\ufe0f ERROR HANDLING\n\n**Common Issues:**\n- Missing shipping address\n- No valid items found\n- File access errors\n- Invalid product types\n\n**Slack Alerts Sent For:**\n- Manual facility assignment needed\n- File validation failures\n- QC issues detected\n- Missing critical data\n\n**Fallback Behavior:**\n- Continues processing valid items\n- Logs errors to Airtable\n- Notifies team via Slack",
        "height": 480,
        "width": 770
      },
      "id": "b53b6581-a7ee-4582-86a2-6d11c1cc22b0",
      "name": "\u26a0\ufe0f Error Handling",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        140,
        -40
      ]
    }
  ],
  "connections": {
    "Shopify HTTP": {
      "main": [
        [
          {
            "node": "Split Orders",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Split Orders": {
      "main": [
        [
          {
            "node": "Merge \u2192 Combine",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Merge \u2192 Combine": {
      "main": [
        [
          {
            "node": "Function - Detect Source",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Function - Detect Source": {
      "main": [
        [
          {
            "node": "Switch",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Switch": {
      "main": [
        [
          {
            "node": "Function - Parse Shopify",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Function - Parse JotForm",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Function - Parse Jiffy",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Stop - Unrecognized Source",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Function - Parse Shopify": {
      "main": [
        []
      ]
    },
    "Function - Parse JotForm": {
      "main": [
        []
      ]
    },
    "Function - Parse Jiffy": {
      "main": [
        [
          {
            "node": "Fix Item Counts",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Store Record IDs": {
      "main": [
        [
          {
            "node": "Add Record IDs to Items",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Add Record IDs to Items": {
      "main": [
        [
          {
            "node": "Upsert Order Items",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Prepare File Records": {
      "main": [
        [
          {
            "node": "Filter Files",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Filter Files": {
      "main": [
        [
          {
            "node": "Airtable - Create Files",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Airtable - Create Files": {
      "main": [
        [
          {
            "node": "Filter Image Files",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Check for Shipments": {
      "main": [
        [
          {
            "node": "Filter Shipments",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Filter Shipments": {
      "main": [
        [
          {
            "node": "Airtable - Create Shipment",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Jiffy Gmail Trigger": {
      "main": [
        [
          {
            "node": "Filter",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "HTTP DTF1": {
      "main": [
        [
          {
            "node": "Tag DTF1",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Tag DTF1": {
      "main": [
        [
          {
            "node": "Merge Forms1",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "HTTP UV1": {
      "main": [
        [
          {
            "node": "Tag UV1",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Tag UV1": {
      "main": [
        [
          {
            "node": "Merge Forms1",
            "type": "main",
            "index": 1
          }
        ]
      ]
    },
    "Merge Forms1": {
      "main": [
        [
          {
            "node": "Split Submissions1",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Split Submissions1": {
      "main": [
        [
          {
            "node": "Merge \u2192 Combine",
            "type": "main",
            "index": 1
          }
        ]
      ]
    },
    "Filter Image Files": {
      "main": [
        [
          {
            "node": "Download File for Analysis",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Download File for Analysis": {
      "main": [
        [
          {
            "node": "Verify Image Type",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Verify Image Type": {
      "main": [
        [
          {
            "node": "Analyze Image API",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Analyze Image API": {
      "main": [
        [
          {
            "node": "Update Files with Analysis",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Update Files with Analysis": {
      "main": [
        [
          {
            "node": "Detect File Issues",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Detect File Issues": {
      "main": [
        [
          {
            "node": "Filter Files with Issues",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Filter Files with Issues": {
      "main": [
        [
          {
            "node": "Slack - File Issues Alert",
            "type": "main",
            "index": 0
          },
          {
            "node": "Prepare Order Item Update",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Slack - File Issues Alert": {
      "main": [
        [
          {
            "node": "Merge Analysis Complete",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Prepare Order Item Update": {
      "main": [
        [
          {
            "node": "Filter Valid Updates",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Filter Valid Updates": {
      "main": [
        [
          {
            "node": "Update Order Item QC",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Update Order Item QC": {
      "main": [
        []
      ]
    },
    "Filter2": {
      "main": [
        [
          {
            "node": "HTML",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "HTML": {
      "main": [
        [
          {
            "node": "Format HTML",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Format HTML": {
      "main": [
        [
          {
            "node": "Merge \u2192 Combine",
            "type": "main",
            "index": 2
          }
        ]
      ]
    },
    "Google Drive": {
      "main": [
        [
          {
            "node": "Google Drive Share File",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Google Drive Share File": {
      "main": [
        [
          {
            "node": "Filter2",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Filter": {
      "main": [
        [
          {
            "node": "Google Drive",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Fix Item Counts": {
      "main": [
        [
          {
            "node": "Upsert Orders",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Process Shipping Label Attachment": {
      "main": [
        [
          {
            "node": "Upload Shipping Label",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Upload Shipping Label": {
      "main": [
        [
          {
            "node": "Upsert Customers",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Upsert Order Items": {
      "main": [
        [
          {
            "node": "Prepare File Records",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Upsert Orders": {
      "main": [
        [
          {
            "node": "Check for Shipments",
            "type": "main",
            "index": 0
          },
          {
            "node": "Process Shipping Label Attachment",
            "type": "main",
            "index": 0
          },
          {
            "node": "Slack - New order",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Upsert Customers": {
      "main": [
        [
          {
            "node": "Store Record IDs",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  },
  "meta": {
    "templateCredsSetupCompleted": true
  }
}