Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
24 commits
Select commit Hold shift + click to select a range
0329997
Chore: Add NotificationPayload TypedDict to schema.py for MercadoPago…
bentoluizv Mar 28, 2025
546d828
Chore: Update database and Redis URLs in settings.toml for containeri…
bentoluizv Mar 30, 2025
13d3be7
Merge branch 'homologacao' into feature/notificacao-pagamentos-mercad…
bentoluizv Mar 30, 2025
609afc6
feat: Add notification endpoint to REST API
bentoluizv Mar 30, 2025
339d403
feat: Change command to run Flask application in Dockerfile for test …
bentoluizv Mar 30, 2025
c54c0b0
feat: Log payload in notification endpoint for debugging purposes
bentoluizv Mar 30, 2025
554b2b5
feat: Log request headers in notification endpoint for improved debug…
bentoluizv Mar 30, 2025
8e035f4
feat: Update database and Redis connection strings in secrets configu…
bentoluizv Mar 30, 2025
5f1e8d5
feat: Restore gunicorn command in Dockerfile for production deployment
bentoluizv Mar 30, 2025
3f43d46
feat: Refactor namespace definitions for improved readability and con…
bentoluizv Mar 30, 2025
b9ff26d
feat: Implement notification endpoint for handling incoming notificat…
bentoluizv Mar 30, 2025
1d9f9cb
feat: Add Docker Compose configuration for backend service
bentoluizv Mar 30, 2025
22dc0c0
feat: Add development configuration for database and notification set…
bentoluizv Mar 30, 2025
881bad1
feat: Add route for notification resource in REST API
bentoluizv Mar 30, 2025
1e69935
fix: Add missing email in clients mock
bentoluizv Mar 31, 2025
f253501
feat: Add function to retrieve payment by MercadoPago ID
bentoluizv Mar 31, 2025
5bc8d96
fix: Change mercadopago_id type from String to Integer in Payment model
bentoluizv Mar 31, 2025
5741047
feat: add Notification model
bentoluizv Mar 31, 2025
a10a986
feat: update database schema for establishment, payment, and product …
bentoluizv Mar 31, 2025
5a4f2a8
feat: add client, establishment, lead, user, order, product, and paym…
bentoluizv Mar 31, 2025
88826ef
feat: enhance Notification resource to handle payment updates and imp…
bentoluizv Mar 31, 2025
87d127c
feat: enhance Notification endpoint to process payment updates with d…
bentoluizv Apr 1, 2025
540944b
feat: add docker-compose configuration for backend service
bentoluizv Apr 1, 2025
a995a2c
docs: update README with installation instructions and Docker usage d…
bentoluizv Apr 1, 2025
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion .secrets.toml
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,11 @@ MERCADOPAGO_ACCESS_TOKEN = "TEST-3070206317287648-031707-c6e11b557ecde6fb4740943


[staging]
SQLALCHEMY_DATABASE_URI = "postgresql://postgres.pnetnjaftmfzgumhgvit:Hampersoujr24@aws-0-sa-east-1.pooler.supabase.com:5432/postgres"
SQLALCHEMY_DATABASE_URI = "postgresql://myuser:mypassword1@postgres:5432/mydatabase"
REDIS_URL = "redis://redis:6379"

[development]
SQLALCHEMY_DATABASE_URI = "postgresql://notification_kjwh_user:yaWtOEKOfnT8Go0rpNl2oMGQYVxjXccQ@dpg-cvkm9q15pdvs73bavtpg-a.oregon-postgres.render.com/notification_kjwh"
REDIS_URL = "rediss://red-cus5n0an91rc73di3440:NCMGqJ6UjrX2Xmf1FwQTFU2kmv75q7Xa@oregon-keyvalue.render.com:6379"


Expand Down
1 change: 1 addition & 0 deletions Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -20,4 +20,5 @@ ENV PATH=/root/.local/bin:$PATH
EXPOSE 5000

CMD ["gunicorn","-w", "4", "-b", "0.0.0.0:5000", "project:create_app()"]
# CMD ["flask","run", "--host", "0.0.0.0", "--port", "5000"]

169 changes: 43 additions & 126 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,182 +6,99 @@ Este é o backend do projeto DeliveryAPP. Ele é construído usando Flask e forn

TODO: Documentar estrutura de pastas e responsabilidades.

## Configuração

### Requisitos
## Requisitos

- Python 3.11
- PostgreSQL
- Redis

### Instalação

1. Clone o repositório:
## Clone o repositório

```bash
```bash=
git clone https://github.com/seuusuario/delivery-app-backend.git
cd delivery-app-backend
```

2. Crie um ambiente virtual e ative-o:
## Rodando Local

```bash
> A aplicação não está rodando na branch main e sim em homologação, não esqueça de fazer:
> `git checkout homologacao`

1. Crie um ambiente virtual e ative-o:

```bash=
python -m venv venv
source venv/bin/activate # No Windows use `venv\Scripts\activate`
```

3. Instale as dependências:
2. Instale as dependências:

```bash
```bash=
pip install -r requirements.txt
```

4. Configure as variáveis de ambiente:
3. Configure as variáveis de ambiente:

```bash
```bash=
export FLASK_APP=project
export FLASK_ENV=local (local | staging | production)
```

5. Rode a aplicação:

```bash
docker compose up
flask run
```

9. Inicialize o banco de dados:

```bash
flask db init
```

10. Migrações

```bash
# para criar uma nova migração
flask db migrate
# para atualizar o banco para a nova migração
flask db upgrade
```

Popule o banco de dados com dados iniciais:

```bash
python scripts/populate_database.py
```

## Executando a Aplicação
4. Rode a aplicação:

### TL:DR

Para executar a aplicação localmente, use o seguinte comando:

```bash
export FLASK_ENV = local
docker compose up
flask run
```bash=
docker compose up # Sobe apenas o banco de dados e redis.
flask run # Roda a aplicação em modo desenvolvimento.
```

### Docker

#### Dockerfile

```bash
FROM python:3.11-slim AS builder

WORKDIR /app
## Rodando com Docker

COPY requirements.txt .
Existem dois arquivos docker-compose no projeto. O docker-compose.yml roda apenas a infra e o docker-compose.backend.yml que sobe o backend.

RUN pip install --upgrade pip && \
pip install --user --no-cache-dir -r requirements.txt
Isso é util para subir a aplicação em modo produção antes de enviar para homologação.

FROM python:3.11-slim

WORKDIR /app

COPY --from=builder /root/.local /root/.local

COPY . .

ENV PATH=/root/.local/bin:$PATH

EXPOSE 5000

CMD ["gunicorn","-w", "4", "-b", "0.0.0.0:5000", "project:create_app()"]
Você pode rodar multiplos arquivos compose adicionando a tag -f.

```bash=
docker-compose -f docker-compose.yml -f docker-compose.backend.yml down
```

#### Docker Compose

1. Arquivo compose com a aplicação, caso FLASK_ENV for "local" você deve subir os serviços com o outro docker-compose.yml listado abaixo
## Banco de dados e Migrações

```bash
services:
backend:
build:
context: .
dockerfile: Dockerfile
container_name: backend
ports:
- "5000:5000"
environment:
- FLASK_ENV=local
- FLASK_APP=project
volumes:
- .:/app
```

2. Compose com a infra, para rodar o ambiente externo localmente, você deve definir as váriaveis de ambiente para local. Para testar com a build que vai para homologação podemos usar em conjunto com o **docker-compose.ext.yml**

```bashs
services:
postgres:
image: postgres:14
container_name: postgres-container
environment:
POSTGRES_DB: mydatabase
POSTGRES_USER: myuser
POSTGRES_PASSWORD: mypassword1
ports:
- "5432:5432"
volumes:
- pgdata:/var/lib/postgresql/data

redis:
image: redis:latest
container_name: redis
ports:
- "6379:6379"

volumes:
pgdata:
```
```bash=
# Inicia a conexão com o banco de dados.
flask db init

para rodar a aplicação local edite FLASK_ENV para **local** e rode o comando:
# Para criar uma nova migração
flask db migrate -m "Pequena descrição sobre o que a nova migração faz"

```bash
docker compose -f docker-compose.yml -f docker-compose.ext.yml
# Para atualizar o banco para a nova migração
flask db upgrade
```

para rodar o ambiente de homologação mude o FLASK_ENV para **staging** e rode:
Popule o banco de dados com dados iniciais:

```bash
docker compose -f docker-compose.ext.yml up
python scripts/populate_database.py
```

Você perceberá que ao tentara executar com FLASK_ENV como **production** você receberá um erro. Isso acontece pois não é possível se conectar ao banco de dados e cache diretamente de uma maquina local. Essa configuração deverá ser usada apenas pelo host da aplicação.

## Ambiente

A aplicação usa Dynaconf para gerenciamento de configuração. A configuração é definida no arquivo `settings.toml`.
A aplicação usa Dynaconf para gerenciamento de configuração. A configuração é definida no arquivo `settings.toml` e `.secrets.toml`.

### Variáveis de Ambiente

- `FLASK_APP`: O nome da aplicação Flask.
- `FLASK_ENV`: O ambiente em que a aplicação está sendo executada (local | staging | production).

## Documentação da API

TODO

## Testes

TODO

## Contato

Para quaisquer perguntas ou problemas, entre em contato com os mantenedores do projeto.
14 changes: 14 additions & 0 deletions docker-compose.backend.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
services:
backend:
build:
context: .
dockerfile: Dockerfile
container_name: backend
ports:
- "5000:5000"
environment:
- FLASK_ENV=staging
- FLASK_APP=project
- PYTHONPATH=./
volumes:
- .:/app
14 changes: 0 additions & 14 deletions docker-compose.yml
Original file line number Diff line number Diff line change
@@ -1,17 +1,4 @@
services:
backend:
build:
context: .
dockerfile: Dockerfile
container_name: backend
ports:
- "5000:5000"
environment:
- FLASK_ENV=staging
- FLASK_APP=project
- PYTHONPATH=./
volumes:
- .:/app
postgres:
image: postgres:14
container_name: postgres-container
Expand All @@ -29,6 +16,5 @@ services:
container_name: redis
ports:
- "6379:6379"

volumes:
pgdata:
9 changes: 6 additions & 3 deletions migrations/env.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ def get_engine():
try:
# this works with Flask-SQLAlchemy<3 and Alchemical
return current_app.extensions['migrate'].db.get_engine()
except TypeError:
except (TypeError, AttributeError):
# this works with Flask-SQLAlchemy>=3
return current_app.extensions['migrate'].db.engine

Expand Down Expand Up @@ -90,14 +90,17 @@ def process_revision_directives(context, revision, directives):
directives[:] = []
logger.info('No changes in schema detected.')

conf_args = current_app.extensions['migrate'].configure_args
if conf_args.get("process_revision_directives") is None:
conf_args["process_revision_directives"] = process_revision_directives

connectable = get_engine()

with connectable.connect() as connection:
context.configure(
connection=connection,
target_metadata=get_metadata(),
process_revision_directives=process_revision_directives,
**current_app.extensions['migrate'].configure_args
**conf_args
)

with context.begin_transaction():
Expand Down
Original file line number Diff line number Diff line change
@@ -1,16 +1,16 @@
"""empty message

Revision ID: 9255441d2a22
Revision ID: fbcd61f123d1
Revises:
Create Date: 2025-03-28 14:45:25.748190
Create Date: 2025-03-31 16:33:11.681985

"""
from alembic import op
import sqlalchemy as sa


# revision identifiers, used by Alembic.
revision = '9255441d2a22'
revision = 'fbcd61f123d1'
down_revision = None
branch_labels = None
depends_on = None
Expand All @@ -36,8 +36,8 @@ def upgrade():

op.create_table('establishment',
sa.Column('id', sa.Integer(), autoincrement=True, nullable=False),
sa.Column('official_name', sa.String(length=40), nullable=False),
sa.Column('fantasy_name', sa.String(length=40), nullable=False),
sa.Column('official_name', sa.String(length=45), nullable=False),
sa.Column('fantasy_name', sa.String(length=45), nullable=False),
sa.Column('cnpj', sa.String(length=14), nullable=False),
sa.Column('telephone', sa.String(length=11), nullable=False),
sa.Column('zip_code', sa.String(length=9), nullable=False),
Expand All @@ -48,7 +48,8 @@ def upgrade():
sa.PrimaryKeyConstraint('id'),
sa.UniqueConstraint('cnpj'),
sa.UniqueConstraint('fantasy_name'),
sa.UniqueConstraint('official_name')
sa.UniqueConstraint('official_name'),
sa.UniqueConstraint('telephone')
)
op.create_table('lead',
sa.Column('id', sa.Integer(), autoincrement=True, nullable=False),
Expand Down Expand Up @@ -108,7 +109,7 @@ def upgrade():
sa.Column('qr_code', sa.String(), nullable=True),
sa.Column('qr_code_base64', sa.Text(), nullable=True),
sa.Column('ticket_url', sa.String(), nullable=True),
sa.Column('mercadopago_id', sa.String(), nullable=True),
sa.Column('mercadopago_id', sa.Integer(), nullable=True),
sa.Column('date_of_expiration', sa.DateTime(), nullable=True),
sa.Column('order_id', sa.Integer(), nullable=True),
sa.ForeignKeyConstraint(['order_id'], ['order.id'], ),
Expand Down
Loading