{
  "name": "afip-sdk-sap-arca-invoice",
  "nodes": [
    {
      "parameters": {
        "path": "sap-pending-document",
        "httpMethod": "POST",
        "responseMode": "onReceived"
      },
      "type": "n8n-nodes-base.webhook",
      "typeVersion": 2,
      "position": [
        0,
        0
      ],
      "id": "sap-pending-document-trigger-63fab1df",
      "name": "SAP pending document trigger"
    },
    {
      "parameters": {
        "method": "GET",
        "url": "https://{{$env.SAP_HOST}}/b1s/v2/Invoices({{$json.docEntry}})",
        "authentication": "genericCredentialType",
        "genericAuthType": "httpHeaderAuth",
        "options": {}
      },
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        240,
        0
      ],
      "id": "get-sap-document-9d36bd3a",
      "name": "Get SAP document"
    },
    {
      "parameters": {
        "jsCode": "const sap = $('Get SAP document').first().json;\nconst lines = sap.DocumentLines || sap.Items || [];\nreturn [{ json: {\n  externalId: 'sap:' + (sap.DocEntry || sap.BillingDocument),\n  sapDocumentId: sap.DocEntry || sap.BillingDocument,\n  companyCode: sap.CompanyCode || sap.BPL_IDAssignedToInvoice,\n  documentType: sap.FederalTaxID ? 80 : 99,\n  documentNumber: sap.FederalTaxID || sap.TaxNumber || 0,\n  customerName: sap.CardName || sap.CustomerName,\n  totalAmount: Number(sap.DocTotal || sap.TotalGrossAmount),\n  netAmount: Number(sap.DocTotal || sap.TotalGrossAmount) / 1.21,\n  vatAmount: Number(sap.DocTotal || sap.TotalGrossAmount) - (Number(sap.DocTotal || sap.TotalGrossAmount) / 1.21),\n  items: lines.map((line) => ({ description: line.ItemDescription || line.Description, quantity: Number(line.Quantity), unitPrice: Number(line.UnitPrice || line.NetPriceAmount), vatRate: 21 }))\n}}];"
      },
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        480,
        0
      ],
      "id": "normalize-fiscal-data-d8a00e4c",
      "name": "Normalize fiscal data"
    },
    {
      "parameters": {
        "additionalFields": {},
        "parametersJson": "{\n  \"environment\": \"dev\",\n  \"tax_id\": \"20409378472\",\n  \"wsid\": \"wsfe\",\n  \"force_create\": false\n}"
      },
      "type": "n8n-nodes-afipsdk.afipSdk",
      "typeVersion": 1,
      "position": [
        720,
        -120
      ],
      "id": "get-arca-authorization-7c4d8073",
      "name": "Get ARCA authorization"
    },
    {
      "parameters": {
        "operation": "makeRequest",
        "parametersJson": "={\n  \"environment\": \"dev\",\n  \"method\": \"FECompUltimoAutorizado\",\n  \"wsid\": \"wsfe\",\n  \"params\": {\n    \"Auth\": {\n      \"Token\": \"{{ $json.token }}\",\n      \"Sign\": \"{{ $json.sign }}\",\n      \"Cuit\": \"20409378472\"\n    },\n    \"PtoVta\": 1,\n    \"CbteTipo\": {{ $('Normalize fiscal data').item.json.voucherType || 11 }}\n  }\n}"
      },
      "type": "n8n-nodes-afipsdk.afipSdk",
      "typeVersion": 1,
      "position": [
        960,
        -120
      ],
      "id": "get-last-voucher-number-52a355ec",
      "name": "Get last voucher number"
    },
    {
      "parameters": {
        "operation": "makeRequest",
        "parametersJson": "={\n  \"environment\": \"dev\",\n  \"method\": \"FECAESolicitar\",\n  \"wsid\": \"wsfe\",\n  \"params\": {\n    \"Auth\": {\n      \"Token\": \"{{ $('Get ARCA authorization').item.json.token }}\",\n      \"Sign\": \"{{ $('Get ARCA authorization').item.json.sign }}\",\n      \"Cuit\": \"20409378472\"\n    },\n    \"FeCAEReq\": {\n      \"FeCabReq\": {\n        \"CantReg\": 1,\n        \"PtoVta\": 1,\n        \"CbteTipo\": {{ $('Normalize fiscal data').item.json.voucherType || 11 }}\n      },\n      \"FeDetReq\": {\n        \"FECAEDetRequest\": {\n          \"Concepto\": 1,\n          \"DocTipo\": {{ $('Normalize fiscal data').item.json.documentType }},\n          \"DocNro\": {{ $('Normalize fiscal data').item.json.documentNumber }},\n          \"CbteDesde\": {{ $json.FECompUltimoAutorizadoResult.CbteNro + 1 }},\n          \"CbteHasta\": {{ $json.FECompUltimoAutorizadoResult.CbteNro + 1 }},\n          \"CbteFch\": {{ new Date().toISOString().slice(0, 10).replace(/-/g, \"\") }},\n          \"ImpTotal\": {{ $('Normalize fiscal data').item.json.totalAmount }},\n          \"ImpTotConc\": 0,\n          \"ImpNeto\": {{ $('Normalize fiscal data').item.json.netAmount }},\n          \"ImpOpEx\": 0,\n          \"ImpIVA\": {{ $('Normalize fiscal data').item.json.vatAmount }},\n          \"ImpTrib\": 0,\n          \"MonId\": \"PES\",\n          \"MonCotiz\": 1,\n          \"CondicionIVAReceptorId\": 5\n        }\n      }\n    }\n  }\n}"
      },
      "type": "n8n-nodes-afipsdk.afipSdk",
      "typeVersion": 1,
      "position": [
        1200,
        0
      ],
      "id": "create-arca-invoice-b3558f3b",
      "name": "Create ARCA invoice"
    },
    {
      "parameters": {
        "resource": "pdf",
        "parametersJson": "={\n  \"template_id\": \"{{ $env.AFIP_SDK_INVOICE_TEMPLATE_ID }}\",\n  \"file_name\": \"{{ $('Normalize fiscal data').item.json.externalId }}.pdf\",\n  \"data\": {\n    \"emitter\": {\n      \"cuit\": \"20409378472\",\n      \"point_of_sale\": 1\n    },\n    \"receiver\": {\n      \"name\": \"{{ $('Normalize fiscal data').item.json.customerName }}\",\n      \"document_type\": {{ $('Normalize fiscal data').item.json.documentType }},\n      \"document_number\": \"{{ $('Normalize fiscal data').item.json.documentNumber }}\"\n    },\n    \"voucher\": {\n      \"type\": {{ $('Normalize fiscal data').item.json.voucherType || 11 }},\n      \"number\": {{ $('Get last voucher number').item.json.FECompUltimoAutorizadoResult.CbteNro + 1 }},\n      \"cae\": \"{{ $('Create ARCA invoice').item.json.FECAESolicitarResult.FeDetResp.FECAEDetResponse.CAE }}\",\n      \"cae_expiration\": \"{{ $('Create ARCA invoice').item.json.FECAESolicitarResult.FeDetResp.FECAEDetResponse.CAEFchVto }}\",\n      \"date\": \"{{ new Date().toISOString().slice(0, 10) }}\"\n    },\n    \"amounts\": {\n      \"net\": {{ $('Normalize fiscal data').item.json.netAmount }},\n      \"vat\": {{ $('Normalize fiscal data').item.json.vatAmount }},\n      \"total\": {{ $('Normalize fiscal data').item.json.totalAmount }}\n    },\n    \"items\": {{ JSON.stringify($('Normalize fiscal data').item.json.items || []) }}\n  }\n}"
      },
      "type": "n8n-nodes-afipsdk.afipSdk",
      "typeVersion": 1,
      "position": [
        1440,
        0
      ],
      "id": "generate-invoice-pdf-sap-arca-invoice",
      "name": "Generate invoice PDF"
    },
    {
      "parameters": {
        "assignments": {
          "assignments": [
            {
              "name": "externalId",
              "value": "={{ $('Normalize fiscal data').item.json.externalId }}",
              "type": "string"
            },
            {
              "name": "cae",
              "value": "={{ $('Create ARCA invoice').item.json.FECAESolicitarResult.FeDetResp.FECAEDetResponse.CAE }}",
              "type": "string"
            },
            {
              "name": "invoiceNumber",
              "value": "={{ $('Get last voucher number').item.json.FECompUltimoAutorizadoResult.CbteNro + 1 }}",
              "type": "number"
            },
            {
              "name": "caeExpiration",
              "value": "={{ $('Create ARCA invoice').item.json.FECAESolicitarResult.FeDetResp.FECAEDetResponse.CAEFchVto }}",
              "type": "string"
            },
            {
              "name": "pdfUrl",
              "value": "={{ $json.file }}",
              "type": "string"
            }
          ]
        },
        "options": {}
      },
      "type": "n8n-nodes-base.set",
      "typeVersion": 3.4,
      "position": [
        1680,
        0
      ],
      "id": "prepare-invoice-result-21c41f80",
      "name": "Prepare invoice result"
    },
    {
      "parameters": {
        "method": "POST",
        "url": "https://{{$env.SAP_HOST}}/b1s/v2/Invoices({{$json.sapDocumentId}})",
        "sendBody": true,
        "bodyParameters": {
          "parameters": [
            {
              "name": "external_id",
              "value": "={{ $json.externalId }}"
            },
            {
              "name": "cae",
              "value": "={{ $json.cae }}"
            },
            {
              "name": "invoice_number",
              "value": "={{ $json.invoiceNumber }}"
            },
            {
              "name": "pdf_url",
              "value": "={{ $json.pdfUrl }}"
            },
            {
              "name": "cae_expiration",
              "value": "={{ $json.caeExpiration }}"
            }
          ]
        },
        "options": {}
      },
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        1920,
        0
      ],
      "id": "update-sap-fiscal-fields-c55c9caf",
      "name": "Update SAP fiscal fields"
    }
  ],
  "pinData": {},
  "connections": {
    "SAP pending document trigger": {
      "main": [
        [
          {
            "node": "Get SAP document",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Get SAP document": {
      "main": [
        [
          {
            "node": "Normalize fiscal data",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Normalize fiscal data": {
      "main": [
        [
          {
            "node": "Get ARCA authorization",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Get ARCA authorization": {
      "main": [
        [
          {
            "node": "Get last voucher number",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Get last voucher number": {
      "main": [
        [
          {
            "node": "Create ARCA invoice",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Create ARCA invoice": {
      "main": [
        [
          {
            "node": "Generate invoice PDF",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Prepare invoice result": {
      "main": [
        [
          {
            "node": "Update SAP fiscal fields",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Generate invoice PDF": {
      "main": [
        [
          {
            "node": "Prepare invoice result",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  },
  "active": false,
  "settings": {
    "executionOrder": "v1"
  },
  "versionId": "template",
  "meta": {
    "templateCredsSetupCompleted": false
  },
  "tags": []
}
