Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature/login form/ac #561

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
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
3 changes: 3 additions & 0 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,5 +3,8 @@
"editor.defaultFormatter": "esbenp.prettier-vscode",
"workbench.editorAssociations": {
"*.md": "vscode.markdown.preview.editor"
},
"[javascriptreact]": {
"editor.defaultFormatter": "vscode.typescript-language-features"
}
}
652 changes: 355 additions & 297 deletions Pipfile.lock

Large diffs are not rendered by default.

202 changes: 121 additions & 81 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,81 +1,121 @@
# WebApp boilerplate with React JS and Flask API

Build web applications using React.js for the front end and python/flask for your backend API.

- Documentation can be found here: https://start.4geeksacademy.com/starters/react-flask
- Here is a video on [how to use this template](https://www.loom.com/share/f37c6838b3f1496c95111e515e83dd9b)
- Integrated with Pipenv for package managing.
- Fast deployment to heroku [in just a few steps here](https://start.4geeksacademy.com/backend/deploy-heroku-posgres).
- Use of .env file.
- SQLAlchemy integration for database abstraction.

### 1) Installation:

> If you use Github Codespaces (recommended) or Gitpod this template will already come with Python, Node and the Posgres Database installed. If you are working locally make sure to install Python 3.10, Node

It is recomended to install the backend first, make sure you have Python 3.8, Pipenv and a database engine (Posgress recomended)

1. Install the python packages: `$ pipenv install`
2. Create a .env file based on the .env.example: `$ cp .env.example .env`
3. Install your database engine and create your database, depending on your database you have to create a DATABASE_URL variable with one of the possible values, make sure you replace the valudes with your database information:

| Engine | DATABASE_URL |
| --------- | --------------------------------------------------- |
| SQLite | sqlite:////test.db |
| MySQL | mysql://username:password@localhost:port/example |
| Postgress | postgres://username:password@localhost:5432/example |

4. Migrate the migrations: `$ pipenv run migrate` (skip if you have not made changes to the models on the `./src/api/models.py`)
5. Run the migrations: `$ pipenv run upgrade`
6. Run the application: `$ pipenv run start`

> Note: Codespaces users can connect to psql by typing: `psql -h localhost -U gitpod example`

### Undo a migration

You are also able to undo a migration by running

```sh
$ pipenv run downgrade
```

### Backend Populate Table Users

To insert test users in the database execute the following command:

```sh
$ flask insert-test-users 5
```

And you will see the following message:

```
Creating test users
[email protected] created.
[email protected] created.
[email protected] created.
[email protected] created.
[email protected] created.
Users created successfully!
```

### **Important note for the database and the data inside it**

Every Github codespace environment will have **its own database**, so if you're working with more people eveyone will have a different database and different records inside it. This data **will be lost**, so don't spend too much time manually creating records for testing, instead, you can automate adding records to your database by editing ```commands.py``` file inside ```/src/api``` folder. Edit line 32 function ```insert_test_data``` to insert the data according to your model (use the function ```insert_test_users``` above as an example). Then, all you need to do is run ```pipenv run insert-test-data```.

### Front-End Manual Installation:

- Make sure you are using node version 14+ and that you have already successfully installed and runned the backend.

1. Install the packages: `$ npm install`
2. Start coding! start the webpack dev server `$ npm run start`

## Publish your website!

This boilerplate it's 100% read to deploy with Render.com and Heroku in a matter of minutes. Please read the [official documentation about it](https://start.4geeksacademy.com/deploy).

### Contributors

This template was built as part of the 4Geeks Academy [Coding Bootcamp](https://4geeksacademy.com/us/coding-bootcamp) by [Alejandro Sanchez](https://twitter.com/alesanchezr) and many other contributors. Find out more about our [Full Stack Developer Course](https://4geeksacademy.com/us/coding-bootcamps/part-time-full-stack-developer), and [Data Science Bootcamp](https://4geeksacademy.com/us/coding-bootcamps/datascience-machine-learning).

You can find other templates and resources like this at the [school github page](https://github.com/4geeksacademy/).
# Aplicación de Gestión Financiera Personal

## Descripción General
Esta aplicación ayuda a los usuarios a registrar sus ingresos, gastos y presupuestos, ofreciendo un análisis detallado de su situación financiera y recomendaciones personalizadas basadas en sus hábitos de consumo. Está diseñada para simplificar la gestión financiera personal con funcionalidades visuales y fáciles de usar.
En el que aparte puede crear grupos de usuarios con el que compartiran las finanzas y un chat en el que estará fromado por los integrantes del grupo para poder comunicarse entre ellos sin necesidad de una aplicación externa.

## Funcionalidades Principales

1. Registro de Transacciones
- Permite a los usuarios registrar ingresos y gastos, categorizándolos (alimentación, transporte, entretenimiento, etc.).
- Agregar detalles como monto, fecha, método de pago y notas adicionales.

2. Gestión de Presupuestos
- Creación y seguimiento de presupuestos mensuales por categorías.
- Alertas si el usuario se acerca a superar el presupuesto.

3. Visualización de Datos
- Gráficos interactivos (barras, pastel, líneas) para mostrar la distribución de gastos e ingresos.
- Resúmenes financieros diarios, semanales y mensuales.

4. Gestión Multidivisa
- Conversión automática de monedas al registrar transacciones en divisas extranjeras, usando una API de tasas de cambio (CurrencyLayer).

5. Autenticación y Seguridad
- Registro de usuarios con correo electrónico y autenticación (por ejemplo, JWT).
- Cifrado de datos sensibles.

6. Integración con Bancos y Tarjetas (Opcional Avanzado)
- Sincronización automática de cuentas bancarias y tarjetas para importar transacciones usando una API como Plaid o FinBox.

7. Grupos de usuarios
- Grupos formados por usuarios en los que son invitados mediante un token o invitacion.
- Compartir las finanzas con el resto de usuarios del grupo.

8- Chat entre usuarios
- Compartir un chat global por cada grupo sin necesidad de usar otra aplicación externa.
- Por ejemplo un chat de telegram o appWrite

8. Otros Extras
- Recordatorios automáticos para pagos recurrentes (facturas, rentas, etc.).
- Modo oscuro y personalización de temas.

## Tecnologías Sugeridas

### Frontend
- **React**: Para construir la interfaz de usuario.
- **Librerías de diseño**: Material-UI, Chakra UI, o TailwindCSS.
- **Librería para gráficos**: Chart.js o Recharts.

### Backend
- **Python con Flask**: Para construir la API.
- **Autenticación**: JWT.
- **Base de datos**: MySQL.

### APIs Externas
- **CurrencyLayer o ExchangeRate-API**: Para conversión de divisas en tiempo real.
- **Plaid API**: Para integración bancaria y automatización de transacciones.
- **Telegram o appWrite**: Para chat global de usuarios.

## Estructura del Proyecto

### Frontend
#### Páginas principales:
- **Login**:
- Donde el usuario podrá acceder a su apartado personal.
- **Singup**:
- El usuario podrá crearse una cuenta para acceder
- Opcional: cifrar contrseñas
- **Inicio**:
- Resumen general de finanzas.
- Gráficos de ingresos/gastos.
- **Registro de Transacciones**:
- Formulario para agregar o editar ingresos y gastos.
- **Presupuesto**:
- Gestión de presupuestos y seguimiento.
- **Finanzas en Grupo**:
- Todos los usuarios comparten las mismas finanzas.
- **Chat global**:
- Donde los usuarios tendrán un chat para comunicarse entre ellos.
- **Análisis**:
- Panel con recomendaciones personalizadas.
- **Configuración**:
- Gestión de cuenta, temas, exportación de datos.

### Backend
#### Endpoints principales:
- `/auth`:
- Registro, inicio de sesión, y autenticación de usuarios.
- `/transactions`:
- CRUD de ingresos y gastos.
- `/budget`:
- Gestión de presupuestos.
- `/analysis`:
- Generación de análisis y recomendaciones.
- `/currency`:
- Conversión de divisas usando una API externa.

#### Base de datos:
- **Tablas principales**:
- **Usuarios**: Información de usuarios.
- **Transacciones**: Detalles de ingresos y gastos.
- **Presupuestos**: Configuración de presupuestos por categorías.
- **Historial de conversión**: Tasas de cambio registradas.
- **Grupos**: Usuarios que forman parte del grupo.

## Desafíos Técnicos

### Sincronización bancaria
- Implementar APIs como Plaid puede requerir configuraciones avanzadas y manejo de datos sensibles.

### Análisis de datos
- Construir algoritmos personalizados para detectar patrones y generar recomendaciones útiles.

### Visualización de gráficos
- Asegurar que las visualizaciones sean interactivas y actualicen datos en tiempo real.

### Escalabilidad
- Manejar múltiples usuarios y grandes volúmenes de datos transaccionales de forma eficiente.

### Chat
- Lograr un chat en tiempo real de usuarios.
1 change: 1 addition & 0 deletions migrations/README
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Single-database configuration for Flask.
50 changes: 50 additions & 0 deletions migrations/alembic.ini
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
# A generic, single database configuration.

[alembic]
# template used to generate migration files
# file_template = %%(rev)s_%%(slug)s

# set to 'true' to run the environment during
# the 'revision' command, regardless of autogenerate
# revision_environment = false


# Logging configuration
[loggers]
keys = root,sqlalchemy,alembic,flask_migrate

[handlers]
keys = console

[formatters]
keys = generic

[logger_root]
level = WARN
handlers = console
qualname =

[logger_sqlalchemy]
level = WARN
handlers =
qualname = sqlalchemy.engine

[logger_alembic]
level = INFO
handlers =
qualname = alembic

[logger_flask_migrate]
level = INFO
handlers =
qualname = flask_migrate

[handler_console]
class = StreamHandler
args = (sys.stderr,)
level = NOTSET
formatter = generic

[formatter_generic]
format = %(levelname)-5.5s [%(name)s] %(message)s
datefmt = %H:%M:%S
113 changes: 113 additions & 0 deletions migrations/env.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
import logging
from logging.config import fileConfig

from flask import current_app

from alembic import context

# this is the Alembic Config object, which provides
# access to the values within the .ini file in use.
config = context.config

# Interpret the config file for Python logging.
# This line sets up loggers basically.
fileConfig(config.config_file_name)
logger = logging.getLogger('alembic.env')


def get_engine():
try:
# this works with Flask-SQLAlchemy<3 and Alchemical
return current_app.extensions['migrate'].db.get_engine()
except (TypeError, AttributeError):
# this works with Flask-SQLAlchemy>=3
return current_app.extensions['migrate'].db.engine


def get_engine_url():
try:
return get_engine().url.render_as_string(hide_password=False).replace(
'%', '%%')
except AttributeError:
return str(get_engine().url).replace('%', '%%')


# add your model's MetaData object here
# for 'autogenerate' support
# from myapp import mymodel
# target_metadata = mymodel.Base.metadata
config.set_main_option('sqlalchemy.url', get_engine_url())
target_db = current_app.extensions['migrate'].db

# other values from the config, defined by the needs of env.py,
# can be acquired:
# my_important_option = config.get_main_option("my_important_option")
# ... etc.


def get_metadata():
if hasattr(target_db, 'metadatas'):
return target_db.metadatas[None]
return target_db.metadata


def run_migrations_offline():
"""Run migrations in 'offline' mode.
This configures the context with just a URL
and not an Engine, though an Engine is acceptable
here as well. By skipping the Engine creation
we don't even need a DBAPI to be available.
Calls to context.execute() here emit the given string to the
script output.
"""
url = config.get_main_option("sqlalchemy.url")
context.configure(
url=url, target_metadata=get_metadata(), literal_binds=True
)

with context.begin_transaction():
context.run_migrations()


def run_migrations_online():
"""Run migrations in 'online' mode.
In this scenario we need to create an Engine
and associate a connection with the context.
"""

# this callback is used to prevent an auto-migration from being generated
# when there are no changes to the schema
# reference: http://alembic.zzzcomputing.com/en/latest/cookbook.html
def process_revision_directives(context, revision, directives):
if getattr(config.cmd_opts, 'autogenerate', False):
script = directives[0]
if script.upgrade_ops.is_empty():
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(),
**conf_args
)

with context.begin_transaction():
context.run_migrations()


if context.is_offline_mode():
run_migrations_offline()
else:
run_migrations_online()
Loading