Skip to content

Commit

Permalink
Update environment configuration, enhance README, and modify admin fu…
Browse files Browse the repository at this point in the history
…nctionalities

- Changed SQL_PASSWORD and DEBUG settings in .env file for local development.
- Expanded README.MD to provide detailed project information, installation steps, and functionalities.
- Updated requirements.txt to include new dependencies and remove unused ones.
- Enhanced admin interface with custom user forms and added a dashboard view for better management.
- Implemented new metrics and configuration models to track business performance.
- Improved error handling in WhatsApp message sending functionality.
- Adjusted serializers and views to incorporate new business logic and validation rules.
  • Loading branch information
UnCubanoDev committed Dec 5, 2024
1 parent 569d12c commit 98928b9
Show file tree
Hide file tree
Showing 75 changed files with 1,968 additions and 1,094 deletions.
6 changes: 3 additions & 3 deletions .env
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
SECRET_KEY=dfe3ffewfwefwe12312&^$%@(&$^()*FDVWje2
SQL_DATABASE=kiki
SQL_USER=postgres
SQL_PASSWORD=9wa8rfj298f98%&jsdf23hf
SQL_PASSWORD=1234
SQL_HOST=localhost
SQL_PORT=5432
SQL_ENGINE=django.db.backends.postgresql
DEBUG=0
DEBUG=1
EMAIL_HOST_USER=uncubanodev@gmail.com
EMAIL_HOST_PASSWORD=ypqszngcbnvyupsv
DJANGO_ALLOWED_HOSTS=*
DJANGO_ALLOWED_HOSTS=["uncubano.dev", "www.uncubano.dev", "localhost", "127.0.0.1"]
45 changes: 45 additions & 0 deletions .github/workflows/development.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
name: Desarrollo

on:
push:
branches:
- develop

jobs:
build:
runs-on: ubuntu-latest

steps:
- name: Checkout del repositorio
uses: actions/checkout@v2

- name: Configurar Python
uses: actions/setup-python@v2
with:
python-version: '3.8'

- name: Instalar dependencias
run: |
python -m venv venv
source venv/bin/activate
pip install -r requirements.txt
- name: Configurar variables de entorno
run: |
echo "SECRET_KEY=tu_secreto" >> $GITHUB_ENV
echo "DEBUG=1" >> $GITHUB_ENV
echo "SQL_DATABASE=kiki_dev" >> $GITHUB_ENV
echo "SQL_USER=postgres" >> $GITHUB_ENV
echo "SQL_PASSWORD=postgres" >> $GITHUB_ENV
echo "SQL_HOST=localhost" >> $GITHUB_ENV
echo "SQL_PORT=5432" >> $GITHUB_ENV
- name: Ejecutar migraciones
run: |
source venv/bin/activate
python manage.py migrate
- name: Ejecutar servidor de desarrollo
run: |
source venv/bin/activate
python manage.py runserver
45 changes: 45 additions & 0 deletions .github/workflows/production.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
name: Producción

on:
push:
branches:
- main

jobs:
build:
runs-on: ubuntu-latest

steps:
- name: Checkout del repositorio
uses: actions/checkout@v2

- name: Configurar Python
uses: actions/setup-python@v2
with:
python-version: '3.8'

- name: Instalar dependencias
run: |
python -m venv venv
source venv/bin/activate
pip install -r requirements.txt
- name: Configurar variables de entorno
run: |
echo "SECRET_KEY=${{ secrets.SECRET_KEY }}" >> $GITHUB_ENV
echo "DEBUG=0" >> $GITHUB_ENV
echo "SQL_DATABASE=${{ secrets.SQL_DATABASE }}" >> $GITHUB_ENV
echo "SQL_USER=${{ secrets.SQL_USER }}" >> $GITHUB_ENV
echo "SQL_PASSWORD=${{ secrets.SQL_PASSWORD }}" >> $GITHUB_ENV
echo "SQL_HOST=${{ secrets.SQL_HOST }}" >> $GITHUB_ENV
echo "SQL_PORT=${{ secrets.SQL_PORT }}" >> $GITHUB_ENV
- name: Ejecutar migraciones
run: |
source venv/bin/activate
python manage.py migrate
- name: Ejecutar servidor de producción
run: |
source venv/bin/activate
gunicorn src.wsgi:application --bind 0.0.0.0:8000
103 changes: 102 additions & 1 deletion README.MD
Original file line number Diff line number Diff line change
@@ -1 +1,102 @@
# Kiki Backend
# Proyecto Kiki

Este proyecto es una aplicación web desarrollada con Django y Django REST Framework, diseñada para gestionar usuarios, direcciones, pedidos y más. Incluye funcionalidades como autenticación, gestión de contraseñas, y un panel de administración personalizado.

## Requisitos

- Python 3.8+
- Django 4.1.1
- PostgreSQL
- Redis (para Channels)
- Node.js (para el servicio de WhatsApp)

## Instalación

1. **Clonar el repositorio:**

```bash
git clone https://github.com/tu_usuario/kiki.git
cd kiki
```

2. **Crear y activar un entorno virtual:**

```bash
python -m venv venv
source venv/bin/activate # En Windows usa `venv\Scripts\activate`
```

3. **Instalar las dependencias:**

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

4. **Configurar las variables de entorno:**

Crea un archivo `.env` en la raíz del proyecto y define las siguientes variables:

```
SECRET_KEY=tu_secreto
DEBUG=1
SQL_DATABASE=kiki
SQL_USER=postgres
SQL_PASSWORD=postgres
SQL_HOST=localhost
SQL_PORT=5432
```

5. **Realizar las migraciones de la base de datos:**

```bash
python manage.py migrate
```

6. **Cargar datos de prueba (opcional):**

```bash
python populate_db.py
```

7. **Ejecutar el servidor de desarrollo:**

```bash
python manage.py runserver
```

## Funcionalidades

- **Autenticación de Usuarios:**

- Registro, inicio de sesión y recuperación de contraseñas.
- Activación de cuenta vía enlace de activación.

- **Gestión de Pedidos:**

- Creación y seguimiento de pedidos.
- Notificaciones de estado de pedidos vía WhatsApp.

- **Panel de Administración:**

- Personalizado con Jazzmin.
- Dashboard con estadísticas de ventas y pedidos.

- **Internacionalización:**
- Soporte para inglés y español.

## Estructura del Proyecto

- `src/`: Contiene la configuración principal de Django.
- `directorio/`: Aplicación para la gestión de usuarios y direcciones.
- `api/`: Aplicación para la gestión de pedidos, productos y configuraciones.
- `templates/`: Plantillas HTML para el frontend.
- `locale/`: Archivos de traducción para internacionalización.


## Despliegue

Este proyecto está configurado para ser desplegado en un VPS usando Docker y GitHub Actions. Asegúrate de configurar correctamente los secretos en GitHub para el despliegue automático.

## Contribuciones

Las contribuciones son bienvenidas. Por favor, sigue el flujo de trabajo de GitHub para enviar tus pull requests.
144 changes: 105 additions & 39 deletions api/admin.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,23 @@
from django.contrib import admin
from django.db.models.query import QuerySet
from django.http.request import HttpRequest
from django.core.exceptions import ValidationError
from django.utils.translation import gettext_lazy as _
from django.contrib import messages
from django.urls import path

from .models import (Restaurant, Category, Distributor, DistributorRating,
OrderDetail, ProductRating, Product, Order, RestaurantRating, Configuration, ProductCategory)
OrderDetail, ProductRating, Product, Order, RestaurantRating, Configuration, ProductCategory, Metrics)

from solo.admin import SingletonModelAdmin
from django.contrib.admin.views.decorators import staff_member_required
from django.utils.decorators import method_decorator
from django.views.generic import TemplateView
from django.db.models import Sum, Count
from django.db.models.functions import TruncDay, TruncMonth, TruncYear
from django.utils import timezone
from datetime import timedelta
from .admin_views import DashboardView


@admin.register(Configuration)
Expand All @@ -18,17 +30,14 @@ class ConfigurationAdmin(SingletonModelAdmin):
class RestaurantAdmin(admin.ModelAdmin):
list_display = [
'name',
'address',
'phone',
'user',
'tax',
'phone',
'is_active',
'recommended',
'rating',
'total_gain',
'total_gain_clean',
'debt',
'funds',
'tax'
]
list_filter = ['is_active']
search_fields = ['name', 'user__username', 'phone']


@admin.register(Category)
Expand All @@ -53,23 +62,78 @@ class DistributorRatingAdmin(admin.ModelAdmin):
pass


@admin.register(OrderDetail)
class OrderDetailAdmin(admin.ModelAdmin):
class OrderDetailInline(admin.TabularInline):
model = OrderDetail
extra = 0
readonly_fields = ['get_final_price']
fields = ['product', 'quantity', 'get_final_price']

def get_final_price(self, obj):
if obj.id:
return obj.get_final_price()
return 0
get_final_price.short_description = _("Precio Final")


@admin.register(Order)
class OrderAdmin(admin.ModelAdmin):
list_display = [
'order',
'product',
'business',
'amount',
'was_paid_by_business',
]
search_fields = [
'order',
'business',
'product',
]
list_filter = [
'was_paid_by_business',
'user',
'date',
'time',
'distributor',
'delivery_address',
'status',
'pay_type',
'get_sub_total',
'delivery_price',
'total_price',
'was_paid_by_distributor',
]
inlines = [OrderDetailInline]

def get_sub_total(self, obj):
return obj.sub_total
get_sub_total.short_description = _("Sub Total")

def formfield_for_foreignkey(self, db_field, request, **kwargs):
if db_field.name == "distributor":
kwargs["queryset"] = Distributor.objects.filter(is_online=True)
return super().formfield_for_foreignkey(db_field, request, **kwargs)

def clean(self, request, obj):
if obj.status != 'pending' and not obj.distributor:
raise ValidationError({
'distributor': _('Se requiere un distribuidor cuando el estado no es "pending"')
})

def save_model(self, request, obj, form, change):
try:
self.clean(request, obj)
super().save_model(request, obj, form, change)
except ValidationError as e:
form._errors.update(e.message_dict)
return

def changeform_view(self, request, object_id=None, form_url='', extra_context=None):
try:
return super().changeform_view(request, object_id, form_url, extra_context)
except ValidationError as e:
form = self.get_form(request)(request.POST)
form._errors = e.message_dict
context = self.get_changeform_initial_data(request)
context.update(extra_context or {})
return self.render_change_form(request, context, form=form, obj=None)


@admin.register(OrderDetail)
class OrderDetailAdmin(admin.ModelAdmin):
list_display = ['order', 'product', 'quantity', 'get_final_price']
readonly_fields = ['get_final_price']

def get_final_price(self, obj):
return obj.get_final_price()
get_final_price.short_description = _("Precio Final")


@admin.register(ProductRating)
Expand Down Expand Up @@ -97,18 +161,20 @@ class RestaurantRatingAdmin(admin.ModelAdmin):
pass


@admin.register(Order)
class OrderAdmin(admin.ModelAdmin):
list_display = [
'user',
'date',
'time',
'distributor',
'delivery_address',
'status',
'pay_type',
'sub_total',
'delivery_price',
'total_price',
'was_paid_by_distributor',
]
admin.site.register(Metrics)


class CustomAdminSite(admin.AdminSite):
def get_urls(self):
urls = super().get_urls()
custom_urls = [
path('dashboard/', self.admin_view(DashboardView.as_view()), name='admin_dashboard'),
]
return custom_urls + urls

def index(self, request, extra_context=None):
extra_context = extra_context or {}
extra_context['show_dashboard'] = True
return super().index(request, extra_context)

admin_site = CustomAdminSite(name='customadmin')
Loading

0 comments on commit 98928b9

Please sign in to comment.