{
  "name": "Contracts Module",
  "nodes": [
    {
      "parameters": {
        "httpMethod": "POST",
        "path": "contracts/create",
        "options": {}
      },
      "name": "Create Contract Webhook",
      "type": "n8n-nodes-base.webhook",
      "typeVersion": 1,
      "position": [
        250,
        300
      ]
    },
    {
      "parameters": {
        "functionCode": "// Extract contract data\nconst data = $input.item.json.body;\n\n// Validate required fields\nif (!data.unit_id || !data.tenant_id || !data.start_date || !data.end_date || !data.monthly_rent || !data.security_deposit) {\n  return {\n    error: true,\n    message: \"Missing required fields: unit_id, tenant_id, start_date, end_date, monthly_rent, and security_deposit are required\"\n  };\n}\n\n// Set default values if not provided\ndata.status = data.status || 'active';\n\nreturn {\n  data,\n  error: false\n};"
      },
      "name": "Validate Contract",
      "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 leases (unit_id, tenant_id, start_date, end_date, monthly_rent, security_deposit, status)\nVALUES ('{{$node[\"Validate Contract\"].json[\"data\"][\"unit_id\"]}}', '{{$node[\"Validate Contract\"].json[\"data\"][\"tenant_id\"]}}', '{{$node[\"Validate Contract\"].json[\"data\"][\"start_date\"]}}', '{{$node[\"Validate Contract\"].json[\"data\"][\"end_date\"]}}', {{$node[\"Validate Contract\"].json[\"data\"][\"monthly_rent\"]}}, {{$node[\"Validate Contract\"].json[\"data\"][\"security_deposit\"]}}, '{{$node[\"Validate Contract\"].json[\"data\"][\"status\"]}}')\nRETURNING id, unit_id, tenant_id, start_date, end_date, monthly_rent, security_deposit, status, created_at;",
        "additionalFields": {}
      },
      "name": "Create Lease",
      "type": "n8n-nodes-base.postgres",
      "typeVersion": 1,
      "position": [
        850,
        400
      ],
      "credentials": {
        "postgres": {
          "name": "<your credential>"
        }
      }
    },
    {
      "parameters": {
        "operation": "executeQuery",
        "query": "UPDATE units SET status = 'occupied' WHERE id = '{{$node[\"Create Lease\"].json[\"rows\"][0][\"unit_id\"]}}'",
        "additionalFields": {}
      },
      "name": "Update Unit Status",
      "type": "n8n-nodes-base.postgres",
      "typeVersion": 1,
      "position": [
        1050,
        400
      ],
      "credentials": {
        "postgres": {
          "name": "<your credential>"
        }
      }
    },
    {
      "parameters": {
        "operation": "executeQuery",
        "query": "SELECT t.first_name, t.last_name, t.email, t.phone, t.whatsapp, t.preferred_contact_method,\n       u.unit_number, p.name as property_name, p.address\nFROM tenants t\nJOIN units u ON u.id = '{{$node[\"Create Lease\"].json[\"rows\"][0][\"unit_id\"]}}'\nJOIN properties p ON u.property_id = p.id\nWHERE t.id = '{{$node[\"Create Lease\"].json[\"rows\"][0][\"tenant_id\"]}}'",
        "additionalFields": {}
      },
      "name": "Get Tenant and Property Details",
      "type": "n8n-nodes-base.postgres",
      "typeVersion": 1,
      "position": [
        1250,
        400
      ],
      "credentials": {
        "postgres": {
          "name": "<your credential>"
        }
      }
    },
    {
      "parameters": {
        "functionCode": "// Prepare welcome message and contract details\nconst lease = $node[\"Create Lease\"].json.rows[0];\nconst tenant = $input.item.json.rows[0];\n\n// Format dates\nconst startDate = new Date(lease.start_date).toLocaleDateString();\nconst endDate = new Date(lease.end_date).toLocaleDateString();\n\n// Format amounts with currency\nconst formattedRent = new Intl.NumberFormat('pt-BR', { style: 'currency', currency: 'BRL' }).format(lease.monthly_rent);\nconst formattedDeposit = new Intl.NumberFormat('pt-BR', { style: 'currency', currency: 'BRL' }).format(lease.security_deposit);\n\n// Create welcome message\nconst welcomeMessage = `*Bem-vindo ao ${tenant.property_name}!*\\n\\nOl\u00e1 ${tenant.first_name},\\n\\nEstamos felizes em t\u00ea-lo como nosso novo inquilino! Seu contrato de aluguel foi registrado com sucesso.\\n\\n*Detalhes do Contrato:*\\nPropriedade: ${tenant.property_name}\\nUnidade: ${tenant.unit_number}\\nEndere\u00e7o: ${tenant.address}\\nData de In\u00edcio: ${startDate}\\nData de T\u00e9rmino: ${endDate}\\nAluguel Mensal: ${formattedRent}\\nDep\u00f3sito de Seguran\u00e7a: ${formattedDeposit}\\n\\nPara qualquer d\u00favida ou assist\u00eancia, voc\u00ea pode entrar em contato conosco atrav\u00e9s deste n\u00famero de WhatsApp.\\n\\nAtenciosamente,\\nEquipe de Administra\u00e7\u00e3o`;\n\n// Create notification for property manager\nconst managerMessage = `Novo Contrato Registrado\\n\\nPropriedade: ${tenant.property_name}\\nUnidade: ${tenant.unit_number}\\nInquilino: ${tenant.first_name} ${tenant.last_name}\\nContato: ${tenant.phone}\\n\\nData de In\u00edcio: ${startDate}\\nData de T\u00e9rmino: ${endDate}\\nAluguel Mensal: ${formattedRent}\\nDep\u00f3sito de Seguran\u00e7a: ${formattedDeposit}\\n\\nID do Contrato: ${lease.id}`;\n\nreturn {\n  welcomeMessage,\n  managerMessage,\n  tenant,\n  lease\n};"
      },
      "name": "Prepare Welcome Message",
      "type": "n8n-nodes-base.function",
      "typeVersion": 1,
      "position": [
        1450,
        400
      ]
    },
    {
      "parameters": {
        "operation": "executeQuery",
        "query": "INSERT INTO messages (tenant_id, direction, channel, content, status)\nVALUES ('{{$node[\"Create Lease\"].json[\"rows\"][0][\"tenant_id\"]}}', 'outgoing', '{{$node[\"Prepare Welcome Message\"].json[\"tenant\"][\"preferred_contact_method\"]}}', '{{$node[\"Prepare Welcome Message\"].json[\"welcomeMessage\"]}}', 'pending')\nRETURNING id;",
        "additionalFields": {}
      },
      "name": "Create Welcome Message",
      "type": "n8n-nodes-base.postgres",
      "typeVersion": 1,
      "position": [
        1650,
        300
      ],
      "credentials": {
        "postgres": {
          "name": "<your credential>"
        }
      }
    },
    {
      "parameters": {
        "operation": "executeQuery",
        "query": "SELECT phone FROM emergency_contacts\nWHERE role = 'property_manager'\nAND property_id = (SELECT property_id FROM units WHERE id = '{{$node[\"Create Lease\"].json[\"rows\"][0][\"unit_id\"]}}')\nORDER BY priority ASC\nLIMIT 1;",
        "additionalFields": {}
      },
      "name": "Get Property Manager",
      "type": "n8n-nodes-base.postgres",
      "typeVersion": 1,
      "position": [
        1650,
        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 Welcome Message\"].json[\"tenant\"][\"whatsapp\"]}}"
            },
            {
              "name": "type",
              "value": "text"
            },
            {
              "name": "text",
              "parameters": [
                {
                  "name": "body",
                  "value": "={{$node[\"Prepare Welcome Message\"].json[\"welcomeMessage\"]}}"
                }
              ]
            }
          ]
        },
        "options": {}
      },
      "name": "Send Welcome Message",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 3,
      "position": [
        1850,
        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 Property Manager\"].json[\"rows\"][0][\"phone\"]}}"
            },
            {
              "name": "type",
              "value": "text"
            },
            {
              "name": "text",
              "parameters": [
                {
                  "name": "body",
                  "value": "={{$node[\"Prepare Welcome Message\"].json[\"managerMessage\"]}}"
                }
              ]
            }
          ]
        },
        "options": {}
      },
      "name": "Notify Property Manager",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 3,
      "position": [
        1850,
        500
      ],
      "credentials": {
        "httpHeaderAuth": {
          "name": "<your credential>"
        }
      }
    },
    {
      "parameters": {
        "respondWith": "json",
        "responseCode": 201,
        "responseData": "={\n  \"success\": true,\n  \"message\": \"Lease created successfully\",\n  \"data\": $node[\"Create Lease\"].json.rows[0]\n}",
        "options": {}
      },
      "name": "Success Response",
      "type": "n8n-nodes-base.respondToWebhook",
      "typeVersion": 1,
      "position": [
        2050,
        400
      ]
    }
  ],
  "connections": {
    "Create Contract Webhook": {
      "main": [
        [
          {
            "node": "Validate Contract",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Validate Contract": {
      "main": [
        [
          {
            "node": "Validation Check",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Validation Check": {
      "main": [
        [
          {
            "node": "Error Response",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Create Lease",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Create Lease": {
      "main": [
        [
          {
            "node": "Update Unit Status",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Update Unit Status": {
      "main": [
        [
          {
            "node": "Get Tenant and Property Details",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Get Tenant and Property Details": {
      "main": [
        [
          {
            "node": "Prepare Welcome Message",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Prepare Welcome Message": {
      "main": [
        [
          {
            "node": "Create Welcome Message",
            "type": "main",
            "index": 0
          },
          {
            "node": "Get Property Manager",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Create Welcome Message": {
      "main": [
        [
          {
            "node": "Send Welcome Message",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Get Property Manager": {
      "main": [
        [
          {
            "node": "Notify Property Manager",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Send Welcome Message": {
      "main": [
        [
          {
            "node": "Success Response",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Notify Property Manager": {
      "main": [
        [
          {
            "node": "Success Response",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  }
}