{
  "name": "Financial Module",
  "nodes": [
    {
      "parameters": {
        "httpMethod": "POST",
        "path": "payments/record",
        "options": {}
      },
      "name": "Record Payment Webhook",
      "type": "n8n-nodes-base.webhook",
      "typeVersion": 1,
      "position": [
        250,
        300
      ]
    },
    {
      "parameters": {
        "functionCode": "// Extract payment data\nconst data = $input.item.json.body;\n\n// Validate required fields\nif (!data.lease_id || !data.amount || !data.payment_date || !data.payment_method) {\n  return {\n    error: true,\n    message: \"Missing required fields: lease_id, amount, payment_date, and payment_method are required\"\n  };\n}\n\n// Set default values if not provided\ndata.status = data.status || 'pending';\ndata.reference_number = data.reference_number || null;\n\nreturn {\n  data,\n  error: false\n};"
      },
      "name": "Validate Payment",
      "type": "n8n-nodes-base.function",
      "typeVersion": 1,
      "position": [
        450,
        300
      ]
    },
    {
      "parameters": {
        "conditions": {
          "string": [
            {
              "value1": "={{$json[\"error\"]}}",
              "operation": "equal",
              "value2": "true"
            }
          ]
        }
      },
      "name": "Validation Check",
      "type": "n8n-nodes-base.if",
      "typeVersion": 1,
      "position": [
        650,
        300
      ]
    },
    {
      "parameters": {
        "respondWith": "json",
        "responseCode": 400,
        "responseData": "={{$json[\"message\"]}}",
        "options": {}
      },
      "name": "Error Response",
      "type": "n8n-nodes-base.respondToWebhook",
      "typeVersion": 1,
      "position": [
        850,
        200
      ]
    },
    {
      "parameters": {
        "operation": "executeQuery",
        "query": "INSERT INTO payments (lease_id, amount, payment_date, payment_method, status, reference_number)\nVALUES ('{{$node[\"Validate Payment\"].json[\"data\"][\"lease_id\"]}}', {{$node[\"Validate Payment\"].json[\"data\"][\"amount\"]}}, '{{$node[\"Validate Payment\"].json[\"data\"][\"payment_date\"]}}', '{{$node[\"Validate Payment\"].json[\"data\"][\"payment_method\"]}}', '{{$node[\"Validate Payment\"].json[\"data\"][\"status\"]}}', {{$node[\"Validate Payment\"].json[\"data\"][\"reference_number\"] ? \"'\" + $node[\"Validate Payment\"].json[\"data\"][\"reference_number\"] + \"'\" : 'NULL'}})\nRETURNING id, lease_id, amount, payment_date, payment_method, status, reference_number, created_at;",
        "additionalFields": {}
      },
      "name": "Record Payment",
      "type": "n8n-nodes-base.postgres",
      "typeVersion": 1,
      "position": [
        850,
        400
      ],
      "credentials": {
        "postgres": {
          "name": "<your credential>"
        }
      }
    },
    {
      "parameters": {
        "operation": "executeQuery",
        "query": "SELECT t.id as tenant_id, t.first_name, t.last_name, t.email, t.phone, t.whatsapp, t.preferred_contact_method,\n       l.monthly_rent, u.unit_number, p.name as property_name\nFROM leases l\nJOIN tenants t ON l.tenant_id = t.id\nJOIN units u ON l.unit_id = u.id\nJOIN properties p ON u.property_id = p.id\nWHERE l.id = '{{$node[\"Record Payment\"].json[\"rows\"][0][\"lease_id\"]}}'",
        "additionalFields": {}
      },
      "name": "Get Tenant and Lease Details",
      "type": "n8n-nodes-base.postgres",
      "typeVersion": 1,
      "position": [
        1050,
        400
      ],
      "credentials": {
        "postgres": {
          "name": "<your credential>"
        }
      }
    },
    {
      "parameters": {
        "functionCode": "// Prepare receipt and notification\nconst payment = $node[\"Record Payment\"].json.rows[0];\nconst tenant = $input.item.json.rows[0];\n\n// Format payment date\nconst paymentDate = new Date(payment.payment_date).toLocaleDateString();\n\n// Format amount with currency\nconst formattedAmount = new Intl.NumberFormat('pt-BR', { style: 'currency', currency: 'BRL' }).format(payment.amount);\n\n// Create receipt message\nconst receiptMessage = `*Payment Receipt*\\n\\nProperty: ${tenant.property_name}\\nUnit: ${tenant.unit_number}\\nTenant: ${tenant.first_name} ${tenant.last_name}\\n\\nAmount: ${formattedAmount}\\nPayment Date: ${paymentDate}\\nPayment Method: ${payment.payment_method}\\nStatus: ${payment.status}\\n${payment.reference_number ? `Reference: ${payment.reference_number}\\n` : ''}\\nReceipt #: ${payment.id.substring(0, 8)}`;\n\n// Create notification for property manager\nconst managerMessage = `New Payment Recorded\\n\\nProperty: ${tenant.property_name}\\nUnit: ${tenant.unit_number}\\nTenant: ${tenant.first_name} ${tenant.last_name}\\n\\nAmount: ${formattedAmount}\\nPayment Date: ${paymentDate}\\nPayment Method: ${payment.payment_method}\\nStatus: ${payment.status}\\n${payment.reference_number ? `Reference: ${payment.reference_number}\\n` : ''}\\nPayment ID: ${payment.id}`;\n\nreturn {\n  receiptMessage,\n  managerMessage,\n  tenant,\n  payment\n};"
      },
      "name": "Prepare Receipt",
      "type": "n8n-nodes-base.function",
      "typeVersion": 1,
      "position": [
        1250,
        400
      ]
    },
    {
      "parameters": {
        "operation": "executeQuery",
        "query": "INSERT INTO messages (tenant_id, direction, channel, content, status)\nVALUES ('{{$node[\"Prepare Receipt\"].json[\"tenant\"][\"tenant_id\"]}}', 'outgoing', '{{$node[\"Prepare Receipt\"].json[\"tenant\"][\"preferred_contact_method\"]}}', '{{$node[\"Prepare Receipt\"].json[\"receiptMessage\"]}}', 'pending')\nRETURNING id;",
        "additionalFields": {}
      },
      "name": "Create Receipt Message",
      "type": "n8n-nodes-base.postgres",
      "typeVersion": 1,
      "position": [
        1450,
        300
      ],
      "credentials": {
        "postgres": {
          "name": "<your credential>"
        }
      }
    },
    {
      "parameters": {
        "operation": "executeQuery",
        "query": "SELECT phone FROM emergency_contacts\nWHERE role = 'financial_manager'\nORDER BY priority ASC\nLIMIT 1;",
        "additionalFields": {}
      },
      "name": "Get Financial Manager",
      "type": "n8n-nodes-base.postgres",
      "typeVersion": 1,
      "position": [
        1450,
        500
      ],
      "credentials": {
        "postgres": {
          "name": "<your credential>"
        }
      }
    },
    {
      "parameters": {
        "method": "POST",
        "url": "https://graph.facebook.com/v17.0/{{$env.WHATSAPP_PHONE_NUMBER_ID}}/messages",
        "authentication": "genericCredentialType",
        "genericAuthType": "httpHeaderAuth",
        "sendBody": true,
        "bodyParameters": {
          "parameters": [
            {
              "name": "messaging_product",
              "value": "whatsapp"
            },
            {
              "name": "recipient_type",
              "value": "individual"
            },
            {
              "name": "to",
              "value": "={{$node[\"Prepare Receipt\"].json[\"tenant\"][\"whatsapp\"]}}"
            },
            {
              "name": "type",
              "value": "text"
            },
            {
              "name": "text",
              "parameters": [
                {
                  "name": "body",
                  "value": "={{$node[\"Prepare Receipt\"].json[\"receiptMessage\"]}}"
                }
              ]
            }
          ]
        },
        "options": {}
      },
      "name": "Send Receipt to Tenant",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 3,
      "position": [
        1650,
        300
      ],
      "credentials": {
        "httpHeaderAuth": {
          "name": "<your credential>"
        }
      }
    },
    {
      "parameters": {
        "method": "POST",
        "url": "https://graph.facebook.com/v17.0/{{$env.WHATSAPP_PHONE_NUMBER_ID}}/messages",
        "authentication": "genericCredentialType",
        "genericAuthType": "httpHeaderAuth",
        "sendBody": true,
        "bodyParameters": {
          "parameters": [
            {
              "name": "messaging_product",
              "value": "whatsapp"
            },
            {
              "name": "recipient_type",
              "value": "individual"
            },
            {
              "name": "to",
              "value": "={{$node[\"Get Financial Manager\"].json[\"rows\"][0][\"phone\"]}}"
            },
            {
              "name": "type",
              "value": "text"
            },
            {
              "name": "text",
              "parameters": [
                {
                  "name": "body",
                  "value": "={{$node[\"Prepare Receipt\"].json[\"managerMessage\"]}}"
                }
              ]
            }
          ]
        },
        "options": {}
      },
      "name": "Notify Financial Manager",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 3,
      "position": [
        1650,
        500
      ],
      "credentials": {
        "httpHeaderAuth": {
          "name": "<your credential>"
        }
      }
    },
    {
      "parameters": {
        "respondWith": "json",
        "responseCode": 201,
        "responseData": "={\n  \"success\": true,\n  \"message\": \"Payment recorded successfully\",\n  \"data\": $node[\"Record Payment\"].json.rows[0]\n}",
        "options": {}
      },
      "name": "Success Response",
      "type": "n8n-nodes-base.respondToWebhook",
      "typeVersion": 1,
      "position": [
        1850,
        400
      ]
    }
  ],
  "connections": {
    "Record Payment Webhook": {
      "main": [
        [
          {
            "node": "Validate Payment",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Validate Payment": {
      "main": [
        [
          {
            "node": "Validation Check",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Validation Check": {
      "main": [
        [
          {
            "node": "Error Response",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Record Payment",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Record Payment": {
      "main": [
        [
          {
            "node": "Get Tenant and Lease Details",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Get Tenant and Lease Details": {
      "main": [
        [
          {
            "node": "Prepare Receipt",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Prepare Receipt": {
      "main": [
        [
          {
            "node": "Create Receipt Message",
            "type": "main",
            "index": 0
          },
          {
            "node": "Get Financial Manager",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Create Receipt Message": {
      "main": [
        [
          {
            "node": "Send Receipt to Tenant",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Get Financial Manager": {
      "main": [
        [
          {
            "node": "Notify Financial Manager",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Send Receipt to Tenant": {
      "main": [
        [
          {
            "node": "Success Response",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Notify Financial Manager": {
      "main": [
        [
          {
            "node": "Success Response",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  }
}