Compare commits
41 Commits
f526330f9e
...
feat/seria
| Author | SHA1 | Date | |
|---|---|---|---|
| b088794716 | |||
| 177b4c01ca | |||
| ea3727363b | |||
| bee35ac5cb | |||
| 85168e24f0 | |||
| 56bbc8f9b4 | |||
|
|
805565aa8e | ||
|
|
4f41156056 | ||
|
|
2438cf2576 | ||
|
|
332884907c | ||
|
|
b2312edff5 | ||
| 4410cc919a | |||
| d1c2b4f1bb | |||
| d57b827e4e | |||
| 1e32cfce7f | |||
| f65b85c7e7 | |||
| ace5091f8b | |||
| de7c32b10f | |||
|
|
b93ee95427 | ||
| 4fcc7c2503 | |||
| 5b373bd15f | |||
| 27b68a9ac2 | |||
| d6b7fe428f | |||
| d9137404a1 | |||
| 3b635cf17a | |||
| d406c734ac | |||
| 193198918b | |||
|
|
1007584d3e | ||
|
|
ac22adb558 | ||
| 2415ed3564 | |||
|
|
539629076f | ||
|
|
7112197ad2 | ||
| 7160d64e86 | |||
| bb5ef7fed8 | |||
| 77761ea8cc | |||
| ff67720cea | |||
| 5e811c802a | |||
| d4a61b8340 | |||
| 52ff61354e | |||
| 8196137c4c | |||
| 47e87e4204 |
39
AGENTS.md
39
AGENTS.md
@@ -159,7 +159,44 @@ Nota: El volumen monta `tienda_ilusion/` en `/app/`, por lo que el path correcto
|
||||
## Tests
|
||||
- Framework: Django unittest
|
||||
- Directorio: don_confiao/tests/
|
||||
- Ejecutar: `docker-compose -f docker-compose.dev.yml run --rm django python manage.py test`
|
||||
- Ejecutar: `docker compose -f docker-compose.dev.yml run --rm django python manage.py test`
|
||||
|
||||
## Workflow TDD (Semáforo Rojo/Verde)
|
||||
|
||||
Todo cambio o nueva funcionalidad debe seguir TDD. **Está prohibido asumir fallos de tests: todo fallo debe ser confirmado ejecutando los tests.**
|
||||
|
||||
### Regla de oro: confirmar antes de modificar
|
||||
Antes de modificar tests (por cambios en comportamiento o por nuevas funcionalidades), **SIEMPRE ejecutar los tests primero** y confirmar que el fallo esperado realmente ocurre. Nunca asumir que un test falla: verificar el fallo con la ejecución real.
|
||||
|
||||
### Ciclo Rojo → Verde → Refactor
|
||||
1. **ROJO (escribir el test y confirmar que falla)**:
|
||||
- Escribir o modificar el test que describe el comportamiento esperado.
|
||||
- Ejecutar los tests **antes de tocar el código de producción**.
|
||||
- Confirmar que el test falla por el motivo esperado (assertion fallida por el comportamiento nuevo, no por error de setup o de importación).
|
||||
- Copiar el output del fallo como evidencia del semáforo rojo.
|
||||
|
||||
2. **VERDE (implementar lo mínimo para que pase)**:
|
||||
- Implementar el código de producción mínimo necesario para que el test pase.
|
||||
- Volver a ejecutar los tests y confirmar que el semáforo queda en verde.
|
||||
|
||||
3. **REFACTOR (limpiar con los tests en verde)**:
|
||||
- Refactorizar y limpiar el código sin cambiar comportamiento.
|
||||
- Re-ejecutar los tests para confirmar que siguen en verde.
|
||||
|
||||
### Ejecutar tests
|
||||
Siempre ejecutar dentro del contenedor de desarrollo:
|
||||
```bash
|
||||
# Test específico (durante el ciclo, preferible sobre el suite completo para ser rápido)
|
||||
docker compose -f docker-compose.dev.yml run --rm django python manage.py test don_confiao.tests.<archivo>
|
||||
|
||||
# Suite completa (al finalizar, para confirmar que nada se rompió)
|
||||
docker compose -f docker-compose.dev.yml run --rm django python manage.py test
|
||||
```
|
||||
|
||||
### Confirmar el fallo, no asumirlo
|
||||
- Si un test falla o se espera que falle, **ejecutarlo y mostrar el resultado** antes de cambiar cualquier código o test.
|
||||
- Verificar que el fallo corresponde a la razón esperada (leer el traceback), no a un problema de entorno, migraciones, importaciones o fixtures.
|
||||
- No modificar tests para "hacerlos pasar" si el fallo no fue previamente confirmado.
|
||||
|
||||
## Comandos Útiles (dentro del contenedor)
|
||||
- Migraciones: `docker-compose -f docker-compose.dev.yml run --rm django python manage.py makemigrations && docker-compose -f docker-compose.dev.yml run --rm django python manage.py migrate`
|
||||
|
||||
361
REFACTORING_SUMMARY.md
Normal file
361
REFACTORING_SUMMARY.md
Normal file
@@ -0,0 +1,361 @@
|
||||
# Refactorización a Domain-Driven Design - Resumen
|
||||
|
||||
## ✅ Refactorización Completada
|
||||
|
||||
**Fecha**: 29 de Mayo 2026
|
||||
**Commit**: `47e87e42048e2394a6461f78d5c8e6a4386aa2f9`
|
||||
**Tests**: 46 tests pasando ✓
|
||||
|
||||
---
|
||||
|
||||
## 📊 Estadísticas
|
||||
|
||||
- **Archivos creados**: 17
|
||||
- **Archivos eliminados**: 2
|
||||
- **Archivos modificados**: 1
|
||||
- **Líneas agregadas**: +816
|
||||
- **Líneas eliminadas**: -621
|
||||
- **Balance neto**: +195 líneas (mejor organización, más documentación)
|
||||
|
||||
---
|
||||
|
||||
## 🏗️ Nueva Estructura
|
||||
|
||||
```
|
||||
don_confiao/
|
||||
├── models/ # ✅ Ya estaba organizado por dominio
|
||||
│ ├── products.py
|
||||
│ ├── customers.py
|
||||
│ ├── sales.py
|
||||
│ ├── payments.py
|
||||
│ └── admin.py
|
||||
│
|
||||
├── serializers/ # 🆕 Nuevo - Organizado por dominio
|
||||
│ ├── __init__.py
|
||||
│ ├── products.py # ProductSerializer, ListProductSerializer
|
||||
│ ├── customers.py # CustomerSerializer, ListCustomerSerializer
|
||||
│ ├── sales.py # Sale, SaleLine, CatalogSale serializers
|
||||
│ └── payments.py # ReconciliationJar, PaymentMethod serializers
|
||||
│
|
||||
├── api/ # 🆕 Nuevo - API Views por dominio
|
||||
│ ├── __init__.py
|
||||
│ ├── products.py # ProductView, ProductsFromTrytonView
|
||||
│ ├── customers.py # CustomerView, CustomersFromTrytonView
|
||||
│ ├── sales.py # SaleView, CatalogSaleView, Sales*TrytonView
|
||||
│ ├── payments.py # ReconciliateJarView, PaymentMethodView
|
||||
│ └── admin.py # AdminCodeValidateView
|
||||
│
|
||||
└── services/ # 🆕 Nuevo - Capa de servicios
|
||||
└── tryton/
|
||||
├── __init__.py
|
||||
├── client.py # Factory + TrytonSale/LineSale
|
||||
├── products.py # ProductTrytonService
|
||||
├── customers.py # CustomerTrytonService
|
||||
└── sales.py # SaleTrytonService
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 📦 Detalles por Dominio
|
||||
|
||||
### 1. Products (Productos)
|
||||
|
||||
**Serializers** (`serializers/products.py`):
|
||||
- `ProductSerializer` - Serializer completo de producto
|
||||
- `ListProductSerializer` - Versión simplificada para listados
|
||||
|
||||
**API Views** (`api/products.py`):
|
||||
- `ProductView` - CRUD de productos con filtrado por `active` status
|
||||
- `ProductsFromTrytonView` - Importación desde Tryton
|
||||
|
||||
**Services** (`services/tryton/products.py`):
|
||||
- `ProductTrytonService` - Lógica de sincronización con Tryton
|
||||
- `import_from_tryton()` - Importa productos
|
||||
- `_create_product()` - Crea nuevo producto
|
||||
- `_update_product()` - Actualiza producto existente
|
||||
- `_need_update()` - Determina si necesita actualización
|
||||
|
||||
---
|
||||
|
||||
### 2. Customers (Clientes)
|
||||
|
||||
**Serializers** (`serializers/customers.py`):
|
||||
- `CustomerSerializer` - Serializer completo de cliente
|
||||
- `ListCustomerSerializer` - Versión simplificada para listados
|
||||
|
||||
**API Views** (`api/customers.py`):
|
||||
- `CustomerView` - CRUD de clientes
|
||||
- `CustomersFromTrytonView` - Importación desde Tryton
|
||||
|
||||
**Services** (`services/tryton/customers.py`):
|
||||
- `CustomerTrytonService` - Lógica de sincronización con Tryton
|
||||
- `import_from_tryton()` - Importa clientes
|
||||
- `_create_customer()` - Crea nuevo cliente
|
||||
- `_update_customer()` - Actualiza cliente existente
|
||||
- `_need_update()` - Determina si necesita actualización
|
||||
|
||||
---
|
||||
|
||||
### 3. Sales (Ventas)
|
||||
|
||||
**Serializers** (`serializers/sales.py`):
|
||||
- `SaleSerializer` - Serializer de venta
|
||||
- `SaleLineSerializer` - Serializer de línea de venta
|
||||
- `CatalogSaleSerializer` - Serializer de venta por catálogo
|
||||
- `CatalogSaleLineSerializer` - Línea de venta por catálogo
|
||||
- `SummarySaleLineSerializer` - Resumen de línea (con detalles)
|
||||
- `SaleSummarySerializer` - Resumen completo de venta
|
||||
- `SaleForRenconciliationSerializer` - Ventas para reconciliación
|
||||
|
||||
**API Views** (`api/sales.py`):
|
||||
- `SaleView` - CRUD de ventas
|
||||
- `CatalogSaleView` - CRUD de ventas por catálogo
|
||||
- `SaleSummary` - Resumen de venta por ID
|
||||
- `SalesForTrytonView` - Exportar ventas a CSV para Tryton
|
||||
- `SalesToTrytonView` - Enviar ventas a Tryton
|
||||
|
||||
**Services** (`services/tryton/sales.py`):
|
||||
- `SaleTrytonService` - Lógica de sincronización con Tryton
|
||||
- `send_to_tryton()` - Envía ventas a Tryton
|
||||
- `_to_tryton_params()` - Convierte venta a formato Tryton
|
||||
|
||||
---
|
||||
|
||||
### 4. Payments (Pagos y Reconciliación)
|
||||
|
||||
**Serializers** (`serializers/payments.py`):
|
||||
- `ReconciliationJarSerializer` - Serializer de arqueo de caja
|
||||
- `PaymentMethodSerializer` - Serializer de métodos de pago
|
||||
|
||||
**API Views** (`api/payments.py`):
|
||||
- `ReconciliateJarView` - Vista de reconciliación (POST/GET)
|
||||
- `ReconciliateJarModelView` - ViewSet para arqueos
|
||||
- `PaymentMethodView` - Listado de métodos de pago
|
||||
- `SalesForReconciliationView` - Ventas pendientes de reconciliación
|
||||
- `Pagination` - Paginación personalizada
|
||||
|
||||
---
|
||||
|
||||
### 5. Admin
|
||||
|
||||
**API Views** (`api/admin.py`):
|
||||
- `AdminCodeValidateView` - Validación de códigos de administrador
|
||||
|
||||
---
|
||||
|
||||
### 6. Services - Tryton Integration
|
||||
|
||||
**Client** (`services/tryton/client.py`):
|
||||
- `get_tryton_client()` - Factory para crear cliente conectado
|
||||
- `TrytonSale` - Representa venta para exportación
|
||||
- `TrytonLineSale` - Representa línea de venta para exportación
|
||||
- Constantes de configuración (HOST, DATABASE, CURRENCY, etc.)
|
||||
|
||||
**Características**:
|
||||
- ✅ Configuración centralizada
|
||||
- ✅ Factory pattern para cliente
|
||||
- ✅ DTOs para transformación de datos
|
||||
- ✅ Reutilizable desde cualquier vista
|
||||
|
||||
---
|
||||
|
||||
## 🔄 Migración de Código
|
||||
|
||||
### Archivos Eliminados
|
||||
|
||||
❌ `serializers.py` (170 líneas) → ✅ `serializers/` (4 archivos)
|
||||
❌ `api_views.py` (526 líneas) → ✅ `api/` (5 archivos)
|
||||
|
||||
### Backwards Compatibility
|
||||
|
||||
Todas las importaciones existentes siguen funcionando gracias a `__init__.py`:
|
||||
|
||||
```python
|
||||
# Antes y Después - Mismas importaciones funcionan
|
||||
from don_confiao.serializers import ProductSerializer
|
||||
from don_confiao.api import ProductView
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🎯 Beneficios Obtenidos
|
||||
|
||||
### 1. Cohesión
|
||||
- Cada módulo agrupa código relacionado a un solo dominio
|
||||
- Fácil encontrar todo lo relacionado a un concepto (ej: productos)
|
||||
|
||||
### 2. Separación de Responsabilidades
|
||||
- **Models**: Definición de datos
|
||||
- **Serializers**: Transformación API ↔ Modelos
|
||||
- **API Views**: Lógica de endpoints
|
||||
- **Services**: Lógica de negocio (Tryton)
|
||||
|
||||
### 3. Mantenibilidad
|
||||
- Archivos más pequeños y enfocados
|
||||
- Menos de 150 líneas por archivo
|
||||
- Más fácil de leer y entender
|
||||
|
||||
### 4. Escalabilidad
|
||||
- Agregar nuevo dominio = crear nuevos archivos en cada capa
|
||||
- No modifica código existente
|
||||
- Open/Closed Principle
|
||||
|
||||
### 5. Testabilidad
|
||||
- Tests pueden organizarse por dominio
|
||||
- Servicios fáciles de mockear
|
||||
- Cada componente testeable independientemente
|
||||
|
||||
### 6. Reutilización
|
||||
- Servicios Tryton usables desde cualquier vista
|
||||
- Serializers compartibles entre vistas
|
||||
- DRY (Don't Repeat Yourself)
|
||||
|
||||
---
|
||||
|
||||
## 📝 Próximos Pasos Sugeridos
|
||||
|
||||
### 1. Organizar Tests por Dominio (Opcional)
|
||||
|
||||
```
|
||||
tests/
|
||||
├── __init__.py
|
||||
├── products/
|
||||
│ ├── test_products_api.py
|
||||
│ ├── test_products_serializers.py
|
||||
│ └── test_products_tryton.py
|
||||
├── customers/
|
||||
│ └── ...
|
||||
└── sales/
|
||||
└── ...
|
||||
```
|
||||
|
||||
### 2. Documentación
|
||||
|
||||
Crear documentación por dominio:
|
||||
```
|
||||
docs/
|
||||
├── products.md
|
||||
├── customers.md
|
||||
├── sales.md
|
||||
└── tryton_integration.md
|
||||
```
|
||||
|
||||
### 3. Mejorar Services Layer
|
||||
|
||||
Agregar más lógica de negocio a services:
|
||||
- Validaciones complejas
|
||||
- Cálculos de negocio
|
||||
- Transformaciones de datos
|
||||
|
||||
### 4. Agregar Type Hints
|
||||
|
||||
Mejorar type hints en services para mejor IDE support:
|
||||
```python
|
||||
def import_from_tryton(self) -> dict[str, list[int]]:
|
||||
"""Importa productos desde Tryton
|
||||
|
||||
Returns:
|
||||
Dict con listas de IDs: checked, failed, updated, created, untouched
|
||||
"""
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🧪 Tests
|
||||
|
||||
### Estado Actual
|
||||
✅ **46 tests pasando**
|
||||
|
||||
### Cobertura por Dominio
|
||||
- ✅ Products: 13 tests (incluye filtrado por active status)
|
||||
- ✅ Sales: 8 tests
|
||||
- ✅ Customers: Tests de integración Tryton
|
||||
- ✅ Payments: Tests de reconciliación
|
||||
- ✅ Admin: Tests de códigos
|
||||
|
||||
### Ejecución
|
||||
```bash
|
||||
# Todos los tests
|
||||
docker compose -f docker-compose.dev.yml run --rm django python manage.py test don_confiao.tests
|
||||
|
||||
# Tests específicos
|
||||
docker compose -f docker-compose.dev.yml run --rm django python manage.py test don_confiao.tests.test_products
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 📚 Ejemplos de Uso
|
||||
|
||||
### Importar Serializers
|
||||
```python
|
||||
# Forma explícita
|
||||
from don_confiao.serializers.products import ProductSerializer
|
||||
|
||||
# Forma simplificada (recomendada)
|
||||
from don_confiao.serializers import ProductSerializer
|
||||
```
|
||||
|
||||
### Importar API Views
|
||||
```python
|
||||
# Forma explícita
|
||||
from don_confiao.api.products import ProductView
|
||||
|
||||
# Forma simplificada (recomendada)
|
||||
from don_confiao.api import ProductView
|
||||
```
|
||||
|
||||
### Usar Services
|
||||
```python
|
||||
from don_confiao.services import get_tryton_client, ProductTrytonService
|
||||
|
||||
# En una vista
|
||||
def my_view(request):
|
||||
client = get_tryton_client()
|
||||
service = ProductTrytonService(client)
|
||||
result = service.import_from_tryton()
|
||||
return Response(result)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🔍 Verificación de Calidad
|
||||
|
||||
### Checks Realizados
|
||||
- ✅ Todos los tests pasan
|
||||
- ✅ Sin imports circulares
|
||||
- ✅ Todas las URLs funcionando
|
||||
- ✅ Backwards compatibility mantenida
|
||||
- ✅ Código limpio y documentado
|
||||
|
||||
### Métricas
|
||||
- **Complejidad ciclomática**: Reducida (archivos más pequeños)
|
||||
- **Acoplamiento**: Reducido (separación de capas)
|
||||
- **Cohesión**: Incrementada (código por dominio)
|
||||
|
||||
---
|
||||
|
||||
## 🎓 Principios Aplicados
|
||||
|
||||
1. **Domain-Driven Design (DDD)**: Organización por dominios de negocio
|
||||
2. **Single Responsibility Principle (SRP)**: Cada módulo una responsabilidad
|
||||
3. **Open/Closed Principle**: Abierto a extensión, cerrado a modificación
|
||||
4. **Dependency Inversion**: Dependencias hacia abstracciones (services)
|
||||
5. **DRY**: Servicios reutilizables, no repetir lógica
|
||||
6. **Separation of Concerns**: Capas bien definidas
|
||||
|
||||
---
|
||||
|
||||
## 📞 Soporte
|
||||
|
||||
Si tienes preguntas sobre la nueva estructura:
|
||||
|
||||
1. **Serializers**: Ver `serializers/__init__.py` para exportaciones
|
||||
2. **API Views**: Ver `api/__init__.py` para exportaciones
|
||||
3. **Services**: Ver `services/tryton/` para lógica Tryton
|
||||
4. **URLs**: Ver `urls.py` para rutas disponibles
|
||||
|
||||
---
|
||||
|
||||
**¡Refactorización completada exitosamente! 🎉**
|
||||
|
||||
La estructura está lista para escalar y mantener de forma eficiente.
|
||||
@@ -44,7 +44,7 @@ services:
|
||||
- media_volume:/app/media
|
||||
- logs_volume:/app/logs
|
||||
ports:
|
||||
- "8000:8000"
|
||||
- "127.0.0.1:9000:8000"
|
||||
depends_on:
|
||||
postgres:
|
||||
condition: service_healthy
|
||||
@@ -57,22 +57,20 @@ services:
|
||||
gunicorn config.wsgi:application --bind 0.0.0.0:8000 --workers 4 --timeout 120"
|
||||
|
||||
# Optional: Nginx reverse proxy para servir archivos estáticos
|
||||
# nginx:
|
||||
# image: nginx:alpine
|
||||
# container_name: tienda_ilusion_nginx
|
||||
# ports:
|
||||
# - "80:80"
|
||||
# - "443:443"
|
||||
# volumes:
|
||||
# - ./nginx.conf:/etc/nginx/nginx.conf:ro
|
||||
# - static_volume:/var/www/static:ro
|
||||
# - media_volume:/var/www/media:ro
|
||||
# - ./ssl:/etc/nginx/ssl:ro
|
||||
# depends_on:
|
||||
# - django
|
||||
# networks:
|
||||
# - tienda_network
|
||||
# restart: unless-stopped
|
||||
nginx:
|
||||
image: nginx:alpine
|
||||
ports:
|
||||
- "10297:80"
|
||||
volumes:
|
||||
- ./nginx.conf:/etc/nginx/nginx.conf:ro
|
||||
- static_volume:/var/www/static
|
||||
- media_volume:/var/www/media
|
||||
- ./dist:/var/www/donconfiao
|
||||
depends_on:
|
||||
- django
|
||||
networks:
|
||||
- tienda_network
|
||||
restart: unless-stopped
|
||||
|
||||
volumes:
|
||||
postgres_data:
|
||||
|
||||
@@ -2,16 +2,12 @@ services:
|
||||
postgres:
|
||||
image: postgres:15-alpine
|
||||
container_name: tienda_ilusion_postgres_staging
|
||||
environment:
|
||||
- POSTGRES_USER=${DB_USER:-tienda_ilusion_user}
|
||||
- POSTGRES_DB=${DB_NAME:-tienda_ilusion_staging}
|
||||
- POSTGRES_PASSWORD=${DB_PASSWORD:-staging_local_password}
|
||||
env_file:
|
||||
- .env.staging
|
||||
volumes:
|
||||
- postgres_staging_data:/var/lib/postgresql/data
|
||||
ports:
|
||||
- "5433:5432" # Puerto diferente para no conflictuar con prod
|
||||
- "5433:5432"
|
||||
networks:
|
||||
- tienda_staging_network
|
||||
restart: unless-stopped
|
||||
@@ -35,9 +31,6 @@ services:
|
||||
environment:
|
||||
- DJANGO_ENV=staging
|
||||
- DB_HOST=postgres
|
||||
- DB_USER=${DB_USER:-tienda_ilusion_user}
|
||||
- DB_NAME=${DB_NAME:-tienda_ilusion_staging}
|
||||
- DB_PASSWORD=${DB_PASSWORD:-staging_local_password}
|
||||
volumes:
|
||||
- ./tienda_ilusion:/app/
|
||||
- static_staging_volume:/app/staticfiles
|
||||
|
||||
36
nginx.conf
Normal file
36
nginx.conf
Normal file
@@ -0,0 +1,36 @@
|
||||
events {
|
||||
worker_connections 1024;
|
||||
}
|
||||
|
||||
http {
|
||||
include /etc/nginx/mime.types;
|
||||
default_type application/octet-stream;
|
||||
|
||||
access_log /var/log/nginx/access.log;
|
||||
error_log /var/log/nginx/error.log;
|
||||
|
||||
server {
|
||||
listen 80;
|
||||
server_name _;
|
||||
client_max_body_size 10M;
|
||||
|
||||
location /media/ {
|
||||
alias /var/www/media/;
|
||||
expires 30d;
|
||||
add_header Cache-Control "public, immutable";
|
||||
}
|
||||
|
||||
location /static/ {
|
||||
alias /var/www/static/;
|
||||
expires 365d;
|
||||
add_header Cache-Control "public, immutable";
|
||||
}
|
||||
|
||||
location / {
|
||||
root /var/www/donconfiao/;
|
||||
try_files $uri /index.html;
|
||||
expires -1;
|
||||
add_header Cache-Control "no-cache";
|
||||
}
|
||||
}
|
||||
}
|
||||
126
poetry.lock
generated
126
poetry.lock
generated
@@ -117,6 +117,115 @@ files = [
|
||||
{file = "mslex-1.3.0.tar.gz", hash = "sha256:641c887d1d3db610eee2af37a8e5abda3f70b3006cdfd2d0d29dc0d1ae28a85d"},
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "pillow"
|
||||
version = "12.2.0"
|
||||
description = "Python Imaging Library (fork)"
|
||||
optional = false
|
||||
python-versions = ">=3.10"
|
||||
groups = ["main"]
|
||||
files = [
|
||||
{file = "pillow-12.2.0-cp310-cp310-macosx_10_10_x86_64.whl", hash = "sha256:a4e8f36e677d3336f35089648c8955c51c6d386a13cf6ee9c189c5f5bd713a9f"},
|
||||
{file = "pillow-12.2.0-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:2e589959f10d9824d39b350472b92f0ce3b443c0a3442ebf41c40cb8361c5b97"},
|
||||
{file = "pillow-12.2.0-cp310-cp310-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:a52edc8bfff4429aaabdf4d9ee0daadbbf8562364f940937b941f87a4290f5ff"},
|
||||
{file = "pillow-12.2.0-cp310-cp310-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:975385f4776fafde056abb318f612ef6285b10a1f12b8570f3647ad0d74b48ec"},
|
||||
{file = "pillow-12.2.0-cp310-cp310-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:bd9c0c7a0c681a347b3194c500cb1e6ca9cab053ea4d82a5cf45b6b754560136"},
|
||||
{file = "pillow-12.2.0-cp310-cp310-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:88d387ff40b3ff7c274947ed3125dedf5262ec6919d83946753b5f3d7c67ea4c"},
|
||||
{file = "pillow-12.2.0-cp310-cp310-musllinux_1_2_aarch64.whl", hash = "sha256:51c4167c34b0d8ba05b547a3bb23578d0ba17b80a5593f93bd8ecb123dd336a3"},
|
||||
{file = "pillow-12.2.0-cp310-cp310-musllinux_1_2_x86_64.whl", hash = "sha256:34c0d99ecccea270c04882cb3b86e7b57296079c9a4aff88cb3b33563d95afaa"},
|
||||
{file = "pillow-12.2.0-cp310-cp310-win32.whl", hash = "sha256:b85f66ae9eb53e860a873b858b789217ba505e5e405a24b85c0464822fe88032"},
|
||||
{file = "pillow-12.2.0-cp310-cp310-win_amd64.whl", hash = "sha256:673aa32138f3e7531ccdbca7b3901dba9b70940a19ccecc6a37c77d5fdeb05b5"},
|
||||
{file = "pillow-12.2.0-cp310-cp310-win_arm64.whl", hash = "sha256:3e080565d8d7c671db5802eedfb438e5565ffa40115216eabb8cd52d0ecce024"},
|
||||
{file = "pillow-12.2.0-cp311-cp311-macosx_10_10_x86_64.whl", hash = "sha256:8be29e59487a79f173507c30ddf57e733a357f67881430449bb32614075a40ab"},
|
||||
{file = "pillow-12.2.0-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:71cde9a1e1551df7d34a25462fc60325e8a11a82cc2e2f54578e5e9a1e153d65"},
|
||||
{file = "pillow-12.2.0-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:f490f9368b6fc026f021db16d7ec2fbf7d89e2edb42e8ec09d2c60505f5729c7"},
|
||||
{file = "pillow-12.2.0-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:8bd7903a5f2a4545f6fd5935c90058b89d30045568985a71c79f5fd6edf9b91e"},
|
||||
{file = "pillow-12.2.0-cp311-cp311-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:3997232e10d2920a68d25191392e3a4487d8183039e1c74c2297f00ed1c50705"},
|
||||
{file = "pillow-12.2.0-cp311-cp311-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:e74473c875d78b8e9d5da2a70f7099549f9eb37ded4e2f6a463e60125bccd176"},
|
||||
{file = "pillow-12.2.0-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:56a3f9c60a13133a98ecff6197af34d7824de9b7b38c3654861a725c970c197b"},
|
||||
{file = "pillow-12.2.0-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:90e6f81de50ad6b534cab6e5aef77ff6e37722b2f5d908686f4a5c9eba17a909"},
|
||||
{file = "pillow-12.2.0-cp311-cp311-win32.whl", hash = "sha256:8c984051042858021a54926eb597d6ee3012393ce9c181814115df4c60b9a808"},
|
||||
{file = "pillow-12.2.0-cp311-cp311-win_amd64.whl", hash = "sha256:6e6b2a0c538fc200b38ff9eb6628228b77908c319a005815f2dde585a0664b60"},
|
||||
{file = "pillow-12.2.0-cp311-cp311-win_arm64.whl", hash = "sha256:9a8a34cc89c67a65ea7437ce257cea81a9dad65b29805f3ecee8c8fe8ff25ffe"},
|
||||
{file = "pillow-12.2.0-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:2d192a155bbcec180f8564f693e6fd9bccff5a7af9b32e2e4bf8c9c69dbad6b5"},
|
||||
{file = "pillow-12.2.0-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:f3f40b3c5a968281fd507d519e444c35f0ff171237f4fdde090dd60699458421"},
|
||||
{file = "pillow-12.2.0-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:03e7e372d5240cc23e9f07deca4d775c0817bffc641b01e9c3af208dbd300987"},
|
||||
{file = "pillow-12.2.0-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:b86024e52a1b269467a802258c25521e6d742349d760728092e1bc2d135b4d76"},
|
||||
{file = "pillow-12.2.0-cp312-cp312-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:7371b48c4fa448d20d2714c9a1f775a81155050d383333e0a6c15b1123dda005"},
|
||||
{file = "pillow-12.2.0-cp312-cp312-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:62f5409336adb0663b7caa0da5c7d9e7bdbaae9ce761d34669420c2a801b2780"},
|
||||
{file = "pillow-12.2.0-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:01afa7cf67f74f09523699b4e88c73fb55c13346d212a59a2db1f86b0a63e8c5"},
|
||||
{file = "pillow-12.2.0-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:fc3d34d4a8fbec3e88a79b92e5465e0f9b842b628675850d860b8bd300b159f5"},
|
||||
{file = "pillow-12.2.0-cp312-cp312-win32.whl", hash = "sha256:58f62cc0f00fd29e64b29f4fd923ffdb3859c9f9e6105bfc37ba1d08994e8940"},
|
||||
{file = "pillow-12.2.0-cp312-cp312-win_amd64.whl", hash = "sha256:7f84204dee22a783350679a0333981df803dac21a0190d706a50475e361c93f5"},
|
||||
{file = "pillow-12.2.0-cp312-cp312-win_arm64.whl", hash = "sha256:af73337013e0b3b46f175e79492d96845b16126ddf79c438d7ea7ff27783a414"},
|
||||
{file = "pillow-12.2.0-cp313-cp313-ios_13_0_arm64_iphoneos.whl", hash = "sha256:8297651f5b5679c19968abefd6bb84d95fe30ef712eb1b2d9b2d31ca61267f4c"},
|
||||
{file = "pillow-12.2.0-cp313-cp313-ios_13_0_arm64_iphonesimulator.whl", hash = "sha256:50d8520da2a6ce0af445fa6d648c4273c3eeefbc32d7ce049f22e8b5c3daecc2"},
|
||||
{file = "pillow-12.2.0-cp313-cp313-ios_13_0_x86_64_iphonesimulator.whl", hash = "sha256:766cef22385fa1091258ad7e6216792b156dc16d8d3fa607e7545b2b72061f1c"},
|
||||
{file = "pillow-12.2.0-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:5d2fd0fa6b5d9d1de415060363433f28da8b1526c1c129020435e186794b3795"},
|
||||
{file = "pillow-12.2.0-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:56b25336f502b6ed02e889f4ece894a72612fe885889a6e8c4c80239ff6e5f5f"},
|
||||
{file = "pillow-12.2.0-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:f1c943e96e85df3d3478f7b691f229887e143f81fedab9b20205349ab04d73ed"},
|
||||
{file = "pillow-12.2.0-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:03f6fab9219220f041c74aeaa2939ff0062bd5c364ba9ce037197f4c6d498cd9"},
|
||||
{file = "pillow-12.2.0-cp313-cp313-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:5cdfebd752ec52bf5bb4e35d9c64b40826bc5b40a13df7c3cda20a2c03a0f5ed"},
|
||||
{file = "pillow-12.2.0-cp313-cp313-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:eedf4b74eda2b5a4b2b2fb4c006d6295df3bf29e459e198c90ea48e130dc75c3"},
|
||||
{file = "pillow-12.2.0-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:00a2865911330191c0b818c59103b58a5e697cae67042366970a6b6f1b20b7f9"},
|
||||
{file = "pillow-12.2.0-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:1e1757442ed87f4912397c6d35a0db6a7b52592156014706f17658ff58bbf795"},
|
||||
{file = "pillow-12.2.0-cp313-cp313-win32.whl", hash = "sha256:144748b3af2d1b358d41286056d0003f47cb339b8c43a9ea42f5fea4d8c66b6e"},
|
||||
{file = "pillow-12.2.0-cp313-cp313-win_amd64.whl", hash = "sha256:390ede346628ccc626e5730107cde16c42d3836b89662a115a921f28440e6a3b"},
|
||||
{file = "pillow-12.2.0-cp313-cp313-win_arm64.whl", hash = "sha256:8023abc91fba39036dbce14a7d6535632f99c0b857807cbbbf21ecc9f4717f06"},
|
||||
{file = "pillow-12.2.0-cp313-cp313t-macosx_10_13_x86_64.whl", hash = "sha256:042db20a421b9bafecc4b84a8b6e444686bd9d836c7fd24542db3e7df7baad9b"},
|
||||
{file = "pillow-12.2.0-cp313-cp313t-macosx_11_0_arm64.whl", hash = "sha256:dd025009355c926a84a612fecf58bb315a3f6814b17ead51a8e48d3823d9087f"},
|
||||
{file = "pillow-12.2.0-cp313-cp313t-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:88ddbc66737e277852913bd1e07c150cc7bb124539f94c4e2df5344494e0a612"},
|
||||
{file = "pillow-12.2.0-cp313-cp313t-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:d362d1878f00c142b7e1a16e6e5e780f02be8195123f164edf7eddd911eefe7c"},
|
||||
{file = "pillow-12.2.0-cp313-cp313t-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:2c727a6d53cb0018aadd8018c2b938376af27914a68a492f59dfcaca650d5eea"},
|
||||
{file = "pillow-12.2.0-cp313-cp313t-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:efd8c21c98c5cc60653bcb311bef2ce0401642b7ce9d09e03a7da87c878289d4"},
|
||||
{file = "pillow-12.2.0-cp313-cp313t-musllinux_1_2_aarch64.whl", hash = "sha256:9f08483a632889536b8139663db60f6724bfcb443c96f1b18855860d7d5c0fd4"},
|
||||
{file = "pillow-12.2.0-cp313-cp313t-musllinux_1_2_x86_64.whl", hash = "sha256:dac8d77255a37e81a2efcbd1fc05f1c15ee82200e6c240d7e127e25e365c39ea"},
|
||||
{file = "pillow-12.2.0-cp313-cp313t-win32.whl", hash = "sha256:ee3120ae9dff32f121610bb08e4313be87e03efeadfc6c0d18f89127e24d0c24"},
|
||||
{file = "pillow-12.2.0-cp313-cp313t-win_amd64.whl", hash = "sha256:325ca0528c6788d2a6c3d40e3568639398137346c3d6e66bb61db96b96511c98"},
|
||||
{file = "pillow-12.2.0-cp313-cp313t-win_arm64.whl", hash = "sha256:2e5a76d03a6c6dcef67edabda7a52494afa4035021a79c8558e14af25313d453"},
|
||||
{file = "pillow-12.2.0-cp314-cp314-ios_13_0_arm64_iphoneos.whl", hash = "sha256:3adc9215e8be0448ed6e814966ecf3d9952f0ea40eb14e89a102b87f450660d8"},
|
||||
{file = "pillow-12.2.0-cp314-cp314-ios_13_0_arm64_iphonesimulator.whl", hash = "sha256:6a9adfc6d24b10f89588096364cc726174118c62130c817c2837c60cf08a392b"},
|
||||
{file = "pillow-12.2.0-cp314-cp314-ios_13_0_x86_64_iphonesimulator.whl", hash = "sha256:6a6e67ea2e6feda684ed370f9a1c52e7a243631c025ba42149a2cc5934dec295"},
|
||||
{file = "pillow-12.2.0-cp314-cp314-macosx_10_15_x86_64.whl", hash = "sha256:2bb4a8d594eacdfc59d9e5ad972aa8afdd48d584ffd5f13a937a664c3e7db0ed"},
|
||||
{file = "pillow-12.2.0-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:80b2da48193b2f33ed0c32c38140f9d3186583ce7d516526d462645fd98660ae"},
|
||||
{file = "pillow-12.2.0-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:22db17c68434de69d8ecfc2fe821569195c0c373b25cccb9cbdacf2c6e53c601"},
|
||||
{file = "pillow-12.2.0-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:7b14cc0106cd9aecda615dd6903840a058b4700fcb817687d0ee4fc8b6e389be"},
|
||||
{file = "pillow-12.2.0-cp314-cp314-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:8cbeb542b2ebc6fcdacabf8aca8c1a97c9b3ad3927d46b8723f9d4f033288a0f"},
|
||||
{file = "pillow-12.2.0-cp314-cp314-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:4bfd07bc812fbd20395212969e41931001fd59eb55a60658b0e5710872e95286"},
|
||||
{file = "pillow-12.2.0-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:9aba9a17b623ef750a4d11b742cbafffeb48a869821252b30ee21b5e91392c50"},
|
||||
{file = "pillow-12.2.0-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:deede7c263feb25dba4e82ea23058a235dcc2fe1f6021025dc71f2b618e26104"},
|
||||
{file = "pillow-12.2.0-cp314-cp314-win32.whl", hash = "sha256:632ff19b2778e43162304d50da0181ce24ac5bb8180122cbe1bf4673428328c7"},
|
||||
{file = "pillow-12.2.0-cp314-cp314-win_amd64.whl", hash = "sha256:4e6c62e9d237e9b65fac06857d511e90d8461a32adcc1b9065ea0c0fa3a28150"},
|
||||
{file = "pillow-12.2.0-cp314-cp314-win_arm64.whl", hash = "sha256:b1c1fbd8a5a1af3412a0810d060a78b5136ec0836c8a4ef9aa11807f2a22f4e1"},
|
||||
{file = "pillow-12.2.0-cp314-cp314t-macosx_10_15_x86_64.whl", hash = "sha256:57850958fe9c751670e49b2cecf6294acc99e562531f4bd317fa5ddee2068463"},
|
||||
{file = "pillow-12.2.0-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:d5d38f1411c0ed9f97bcb49b7bd59b6b7c314e0e27420e34d99d844b9ce3b6f3"},
|
||||
{file = "pillow-12.2.0-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:5c0a9f29ca8e79f09de89293f82fc9b0270bb4af1d58bc98f540cc4aedf03166"},
|
||||
{file = "pillow-12.2.0-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:1610dd6c61621ae1cf811bef44d77e149ce3f7b95afe66a4512f8c59f25d9ebe"},
|
||||
{file = "pillow-12.2.0-cp314-cp314t-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:0a34329707af4f73cf1782a36cd2289c0368880654a2c11f027bcee9052d35dd"},
|
||||
{file = "pillow-12.2.0-cp314-cp314t-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:8e9c4f5b3c546fa3458a29ab22646c1c6c787ea8f5ef51300e5a60300736905e"},
|
||||
{file = "pillow-12.2.0-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:fb043ee2f06b41473269765c2feae53fc2e2fbf96e5e22ca94fb5ad677856f06"},
|
||||
{file = "pillow-12.2.0-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:f278f034eb75b4e8a13a54a876cc4a5ab39173d2cdd93a638e1b467fc545ac43"},
|
||||
{file = "pillow-12.2.0-cp314-cp314t-win32.whl", hash = "sha256:6bb77b2dcb06b20f9f4b4a8454caa581cd4dd0643a08bacf821216a16d9c8354"},
|
||||
{file = "pillow-12.2.0-cp314-cp314t-win_amd64.whl", hash = "sha256:6562ace0d3fb5f20ed7290f1f929cae41b25ae29528f2af1722966a0a02e2aa1"},
|
||||
{file = "pillow-12.2.0-cp314-cp314t-win_arm64.whl", hash = "sha256:aa88ccfe4e32d362816319ed727a004423aab09c5cea43c01a4b435643fa34eb"},
|
||||
{file = "pillow-12.2.0-pp311-pypy311_pp73-macosx_10_15_x86_64.whl", hash = "sha256:0538bd5e05efec03ae613fd89c4ce0368ecd2ba239cc25b9f9be7ed426b0af1f"},
|
||||
{file = "pillow-12.2.0-pp311-pypy311_pp73-macosx_11_0_arm64.whl", hash = "sha256:394167b21da716608eac917c60aa9b969421b5dcbbe02ae7f013e7b85811c69d"},
|
||||
{file = "pillow-12.2.0-pp311-pypy311_pp73-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:5d04bfa02cc2d23b497d1e90a0f927070043f6cbf303e738300532379a4b4e0f"},
|
||||
{file = "pillow-12.2.0-pp311-pypy311_pp73-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:0c838a5125cee37e68edec915651521191cef1e6aa336b855f495766e77a366e"},
|
||||
{file = "pillow-12.2.0-pp311-pypy311_pp73-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:4a6c9fa44005fa37a91ebfc95d081e8079757d2e904b27103f4f5fa6f0bf78c0"},
|
||||
{file = "pillow-12.2.0-pp311-pypy311_pp73-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:25373b66e0dd5905ed63fa3cae13c82fbddf3079f2c8bf15c6fb6a35586324c1"},
|
||||
{file = "pillow-12.2.0-pp311-pypy311_pp73-win_amd64.whl", hash = "sha256:bfa9c230d2fe991bed5318a5f119bd6780cda2915cca595393649fc118ab895e"},
|
||||
{file = "pillow-12.2.0.tar.gz", hash = "sha256:a830b1a40919539d07806aa58e1b114df53ddd43213d9c8b75847eee6c0182b5"},
|
||||
]
|
||||
|
||||
[package.extras]
|
||||
docs = ["furo", "olefile", "sphinx (>=8.2)", "sphinx-autobuild", "sphinx-copybutton", "sphinx-inline-tabs", "sphinxext-opengraph"]
|
||||
fpx = ["olefile"]
|
||||
mic = ["olefile"]
|
||||
test-arrow = ["arro3-compute", "arro3-core", "nanoarrow", "pyarrow"]
|
||||
tests = ["check-manifest", "coverage (>=7.4.2)", "defusedxml", "markdown2", "olefile", "packaging", "pyroma (>=5)", "pytest", "pytest-cov", "pytest-timeout", "pytest-xdist", "trove-classifiers (>=2024.10.12)"]
|
||||
xmp = ["defusedxml"]
|
||||
|
||||
[[package]]
|
||||
name = "psutil"
|
||||
version = "6.1.1"
|
||||
@@ -282,7 +391,22 @@ files = [
|
||||
{file = "tzdata-2026.2.tar.gz", hash = "sha256:9173fde7d80d9018e02a662e168e5a2d04f87c41ea174b139fbef642eda62d10"},
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "whitenoise"
|
||||
version = "6.12.0"
|
||||
description = "Radically simplified static file serving for WSGI applications"
|
||||
optional = false
|
||||
python-versions = ">=3.10"
|
||||
groups = ["main"]
|
||||
files = [
|
||||
{file = "whitenoise-6.12.0-py3-none-any.whl", hash = "sha256:fc5e8c572e33ebf24795b47b6a7da8da3c00cff2349f5b04c02f28d0cc5a3cc2"},
|
||||
{file = "whitenoise-6.12.0.tar.gz", hash = "sha256:f723ebb76a112e98816ff80fcea0a6c9b8ecde835f8ddda25df7a30a3c2db6ad"},
|
||||
]
|
||||
|
||||
[package.extras]
|
||||
brotli = ["brotli"]
|
||||
|
||||
[metadata]
|
||||
lock-version = "2.1"
|
||||
python-versions = ">=3.14,<4.0"
|
||||
content-hash = "02efc37f4afc4dbe36959374dba58e3b6e61be3f8c4298427009b9ee0d3a1910"
|
||||
content-hash = "ac185d7c04ec39d561c6cc78d022accbdc80e2f815f39c71aa5f38c6502f70b2"
|
||||
|
||||
@@ -12,7 +12,9 @@ dependencies = [
|
||||
"djangorestframework (>=3.17.1,<4.0.0)",
|
||||
"django-cors-headers (>=4.9.0,<5.0.0)",
|
||||
"djangorestframework-simplejwt (>=5.5.1,<6.0.0)",
|
||||
"sabatron-tryton-rpc-client (>=7.4.0,<8.0.0)"
|
||||
"sabatron-tryton-rpc-client (>=7.4.0,<8.0.0)",
|
||||
"pillow (>=12.2.0,<13.0.0)",
|
||||
"whitenoise (>=6.12.0,<7.0.0)"
|
||||
]
|
||||
|
||||
|
||||
|
||||
@@ -15,3 +15,4 @@ python-decouple # Manage environment variables and settings
|
||||
|
||||
# Static files serving in production/staging
|
||||
whitenoise==6.6.0 # Serve static files efficiently with compression
|
||||
Pillow # Image processing for catalogue image resizing
|
||||
|
||||
80
scripts/fill_sale_codes.py
Normal file
80
scripts/fill_sale_codes.py
Normal file
@@ -0,0 +1,80 @@
|
||||
#!/usr/bin/env python3
|
||||
import argparse
|
||||
import getpass
|
||||
import sys
|
||||
|
||||
import requests
|
||||
|
||||
|
||||
TOKEN_URL = "/api/token/"
|
||||
FILL_SALES_CODES_URL = "/don_confiao/api/sales/fill_codes/"
|
||||
FILL_CATALOG_SALES_CODES_URL = "/don_confiao/api/catalog_sales/fill_codes/"
|
||||
|
||||
|
||||
def get_credentials():
|
||||
username = input("Usuario: ")
|
||||
password = getpass.getpass("Contraseña: ")
|
||||
return username, password
|
||||
|
||||
|
||||
def get_token(domain, username, password):
|
||||
url = domain.rstrip("/") + TOKEN_URL
|
||||
response = requests.post(
|
||||
url, json={"username": username, "password": password}
|
||||
)
|
||||
if response.status_code != 200:
|
||||
print(
|
||||
f"Error al obtener token: {response.status_code} {response.text}",
|
||||
file=sys.stderr,
|
||||
)
|
||||
sys.exit(1)
|
||||
return response.json()["access"]
|
||||
|
||||
|
||||
def fill_codes(domain, token, url):
|
||||
headers = {"Authorization": f"Bearer {token}"}
|
||||
full_url = domain.rstrip("/") + url
|
||||
response = requests.post(full_url, headers=headers)
|
||||
if response.status_code != 200:
|
||||
print(
|
||||
f"Error al llenar códigos ({url}): {response.status_code} {response.text}",
|
||||
file=sys.stderr,
|
||||
)
|
||||
sys.exit(1)
|
||||
return response.json()
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(
|
||||
description="Asigna un código único a todas las ventas y pedidos que lo requieran."
|
||||
)
|
||||
parser.add_argument(
|
||||
"domain", help="Dominio del backend (ej: http://localhost:8000)"
|
||||
)
|
||||
args = parser.parse_args()
|
||||
|
||||
username, password = get_credentials()
|
||||
token = get_token(args.domain, username, password)
|
||||
print("Token obtenido correctamente.")
|
||||
|
||||
print("Asignando códigos a ventas...")
|
||||
sales_result = fill_codes(args.domain, token, FILL_SALES_CODES_URL)
|
||||
print(f" [OK] Ventas actualizadas: {sales_result['sales_updated']}")
|
||||
|
||||
print("Asignando códigos a pedidos de catálogo...")
|
||||
catalog_result = fill_codes(
|
||||
args.domain, token, FILL_CATALOG_SALES_CODES_URL
|
||||
)
|
||||
print(
|
||||
f" [OK] Pedidos de catálogo actualizados: "
|
||||
f"{catalog_result['catalog_sales_updated']}"
|
||||
)
|
||||
|
||||
print(
|
||||
f"\nResumen: {sales_result['sales_updated']} ventas, "
|
||||
f"{catalog_result['catalog_sales_updated']} pedidos de catálogo actualizados"
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
99
scripts/reupload_catalogue_images.py
Executable file
99
scripts/reupload_catalogue_images.py
Executable file
@@ -0,0 +1,99 @@
|
||||
#!/usr/bin/env python3
|
||||
import argparse
|
||||
import getpass
|
||||
import sys
|
||||
|
||||
import requests
|
||||
|
||||
|
||||
TOKEN_URL = "/api/token/"
|
||||
CATALOGUE_IMAGES_URL = "/don_confiao/api/catalogue_images/"
|
||||
|
||||
|
||||
def get_credentials():
|
||||
username = input("Usuario: ")
|
||||
password = getpass.getpass("Contraseña: ")
|
||||
return username, password
|
||||
|
||||
|
||||
def get_token(domain, username, password):
|
||||
url = domain.rstrip("/") + TOKEN_URL
|
||||
response = requests.post(url, json={"username": username, "password": password})
|
||||
if response.status_code != 200:
|
||||
print(f"Error al obtener token: {response.status_code} {response.text}", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
data = response.json()
|
||||
return data["access"]
|
||||
|
||||
|
||||
def get_catalogue_images(domain, token):
|
||||
url = domain.rstrip("/") + CATALOGUE_IMAGES_URL
|
||||
headers = {"Authorization": f"Bearer {token}"}
|
||||
response = requests.get(url, headers=headers)
|
||||
if response.status_code != 200:
|
||||
print(f"Error al obtener imágenes de catálogo: {response.status_code} {response.text}", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
return response.json()
|
||||
|
||||
|
||||
def download_image(image_url):
|
||||
response = requests.get(image_url)
|
||||
if response.status_code != 200:
|
||||
print(f" [ERR] No se pudo descargar imagen: {response.status_code}", file=sys.stderr)
|
||||
return None
|
||||
return response.content
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(
|
||||
description="Vuelve a subir cada imagen de catálogo existente para forzar el redimensionado."
|
||||
)
|
||||
parser.add_argument("domain", help="Dominio del backend (ej: http://localhost:8000)")
|
||||
args = parser.parse_args()
|
||||
|
||||
username, password = get_credentials()
|
||||
token = get_token(args.domain, username, password)
|
||||
print("Token obtenido correctamente.")
|
||||
|
||||
images = get_catalogue_images(args.domain, token)
|
||||
if not images:
|
||||
print("No hay imágenes de catálogo para procesar.")
|
||||
return
|
||||
|
||||
headers = {"Authorization": f"Bearer {token}"}
|
||||
updated = 0
|
||||
errors = 0
|
||||
|
||||
for img in images:
|
||||
ci_id = img["id"]
|
||||
product_id = img["product"]
|
||||
image_url = img["image"]
|
||||
|
||||
print(f" [{ci_id}] Descargando {image_url} ...")
|
||||
content = download_image(image_url)
|
||||
if content is None:
|
||||
errors += 1
|
||||
continue
|
||||
|
||||
# Determine content type from URL extension
|
||||
ext = image_url.rsplit(".", 1)[-1].lower() if "." in image_url else "jpg"
|
||||
mime = {"jpg": "image/jpeg", "jpeg": "image/jpeg", "png": "image/png"}.get(ext, "application/octet-stream")
|
||||
filename = f"image.{ext}"
|
||||
|
||||
update_url = args.domain.rstrip("/") + CATALOGUE_IMAGES_URL.rstrip("/") + f"/{ci_id}/"
|
||||
files = {"image": (filename, content, mime)}
|
||||
data = {"product": product_id}
|
||||
response = requests.put(update_url, headers=headers, files=files, data=data)
|
||||
|
||||
if response.status_code == 200:
|
||||
print(f" [OK] Imagen {ci_id} (producto {product_id}) actualizada.")
|
||||
updated += 1
|
||||
else:
|
||||
print(f" [ERR] Imagen {ci_id}: {response.status_code} {response.text}")
|
||||
errors += 1
|
||||
|
||||
print(f"\nResumen: {updated} actualizadas, {errors} errores")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
126
scripts/upload_catalogue_images.py
Executable file
126
scripts/upload_catalogue_images.py
Executable file
@@ -0,0 +1,126 @@
|
||||
#!/usr/bin/env python3
|
||||
import argparse
|
||||
import getpass
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import requests
|
||||
|
||||
|
||||
TOKEN_URL = "/api/token/"
|
||||
PRODUCTS_URL = "/don_confiao/api/products/"
|
||||
CATALOGUE_IMAGES_URL = "/don_confiao/api/catalogue_images/"
|
||||
|
||||
|
||||
def get_credentials():
|
||||
username = input("Usuario: ")
|
||||
password = getpass.getpass("Contraseña: ")
|
||||
return username, password
|
||||
|
||||
|
||||
def get_token(domain, username, password):
|
||||
url = domain.rstrip("/") + TOKEN_URL
|
||||
response = requests.post(url, json={"username": username, "password": password})
|
||||
if response.status_code != 200:
|
||||
print(f"Error al obtener token: {response.status_code} {response.text}", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
data = response.json()
|
||||
return data["access"]
|
||||
|
||||
|
||||
def get_products(domain, token):
|
||||
url = domain.rstrip("/") + PRODUCTS_URL
|
||||
headers = {"Authorization": f"Bearer {token}"}
|
||||
response = requests.get(url, headers=headers)
|
||||
if response.status_code != 200:
|
||||
print(f"Error al obtener productos: {response.status_code} {response.text}", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
return response.json()
|
||||
|
||||
|
||||
MIME_TYPES = {
|
||||
".jpg": "image/jpeg",
|
||||
".jpeg": "image/jpeg",
|
||||
".png": "image/png",
|
||||
}
|
||||
|
||||
|
||||
def find_images(image_dir):
|
||||
images = {}
|
||||
pattern = re.compile(r"^(\d+)\.(jpg|jpeg|png)$", re.IGNORECASE)
|
||||
for f in os.listdir(image_dir):
|
||||
m = pattern.match(f)
|
||||
if m:
|
||||
external_id = m.group(1)
|
||||
images[external_id] = os.path.join(image_dir, f)
|
||||
return images
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(
|
||||
description="Sube imágenes de catálogo para productos usando el external_id como nombre de archivo."
|
||||
)
|
||||
parser.add_argument("image_dir", help="Directorio con imágenes nombradas como ##.jpg")
|
||||
parser.add_argument("domain", help="Dominio del backend (ej: http://localhost:8000)")
|
||||
args = parser.parse_args()
|
||||
|
||||
if not os.path.isdir(args.image_dir):
|
||||
print(f"Error: el directorio '{args.image_dir}' no existe.", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
|
||||
username, password = get_credentials()
|
||||
token = get_token(args.domain, username, password)
|
||||
print("Token obtenido correctamente.")
|
||||
|
||||
products = get_products(args.domain, token)
|
||||
ext_id_to_product_id = {}
|
||||
for p in products:
|
||||
if p.get("external_id"):
|
||||
ext_id_to_product_id[p["external_id"]] = p["id"]
|
||||
|
||||
if not ext_id_to_product_id:
|
||||
print("No se encontraron productos con external_id.", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
|
||||
images = find_images(args.image_dir)
|
||||
if not images:
|
||||
print(f"No se encontraron imágenes con el patrón ##.jpg en '{args.image_dir}'.", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
|
||||
headers = {"Authorization": f"Bearer {token}"}
|
||||
upload_url = args.domain.rstrip("/") + CATALOGUE_IMAGES_URL
|
||||
uploaded = 0
|
||||
skipped = 0
|
||||
errors = 0
|
||||
|
||||
for external_id, img_path in sorted(images.items()):
|
||||
if external_id not in ext_id_to_product_id:
|
||||
print(f" [SKIP] {Path(img_path).name}: no hay producto con external_id={external_id}")
|
||||
skipped += 1
|
||||
continue
|
||||
|
||||
product_id = ext_id_to_product_id[external_id]
|
||||
filename = Path(img_path).name
|
||||
|
||||
ext = Path(img_path).suffix.lower()
|
||||
mime = MIME_TYPES.get(ext, "application/octet-stream")
|
||||
|
||||
with open(img_path, "rb") as f:
|
||||
files = {"image": (filename, f, mime)}
|
||||
data = {"product": product_id}
|
||||
response = requests.post(upload_url, headers=headers, files=files, data=data)
|
||||
|
||||
if response.status_code == 201:
|
||||
print(f" [OK] {filename} -> producto {product_id} (id imagen: {response.json()['id']})")
|
||||
uploaded += 1
|
||||
else:
|
||||
print(f" [ERR] {filename} -> producto {product_id}: {response.status_code} {response.text}")
|
||||
errors += 1
|
||||
|
||||
print(f"\nResumen: {uploaded} subidas, {skipped} saltadas, {errors} errores")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -138,6 +138,23 @@ USE_TZ = True
|
||||
STATIC_URL = "static/"
|
||||
STATIC_ROOT = BASE_DIR / "staticfiles"
|
||||
|
||||
# Media files
|
||||
MEDIA_ROOT = BASE_DIR / "media"
|
||||
MEDIA_URL = "/media/"
|
||||
|
||||
# Catalogue image settings
|
||||
CATALOGUE_IMAGE_WIDTH = int(os.environ.get("CATALOGUE_IMAGE_WIDTH", "600"))
|
||||
CATALOGUE_IMAGE_HEIGHT = int(os.environ.get("CATALOGUE_IMAGE_HEIGHT", "600"))
|
||||
CATALOGUE_STRICT_DIMENSION = os.environ.get("CATALOGUE_STRICT_DIMENSION", "False").lower() in ("true", "1", "yes")
|
||||
CATALOGUE_BACKGROUND_IMAGES_RGBA = os.environ.get(
|
||||
"CATALOGUE_BACKGROUND_IMAGES_RGBA", "0,0,0,0"
|
||||
)
|
||||
# Parse RGBA string to tuple
|
||||
_rgba_parts = CATALOGUE_BACKGROUND_IMAGES_RGBA.split(",")
|
||||
CATALOGUE_BACKGROUND_IMAGES_RGBA = tuple(int(p.strip()) for p in _rgba_parts)
|
||||
CATALOGUE_MAX_UPLOAD_SIZE = int(os.environ.get("CATALOGUE_MAX_UPLOAD_SIZE", str(5 * 1024 * 1024)))
|
||||
LOGO_MAX_UPLOAD_SIZE = int(os.environ.get("LOGO_MAX_UPLOAD_SIZE", str(5 * 1024 * 1024)))
|
||||
|
||||
# Default primary key field type
|
||||
# https://docs.djangoproject.com/en/5.0/ref/settings/#default-auto-field
|
||||
|
||||
@@ -150,7 +167,7 @@ REST_FRAMEWORK = {
|
||||
"rest_framework_simplejwt.authentication.JWTAuthentication",
|
||||
],
|
||||
"DEFAULT_PERMISSION_CLASSES": [
|
||||
"rest_framework.permissions.IsAuthenticated",
|
||||
"rest_framework.permissions.AllowAny",
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
@@ -48,6 +48,10 @@ EMAIL_BACKEND = "django.core.mail.backends.console.EmailBackend"
|
||||
STATIC_ROOT = BASE_DIR / "staticfiles"
|
||||
STATIC_URL = "/static/"
|
||||
|
||||
# Media files configuration
|
||||
MEDIA_ROOT = BASE_DIR / "media"
|
||||
MEDIA_URL = "/media/"
|
||||
|
||||
# WhiteNoise configuration for development (optional, for consistency)
|
||||
# In development with DEBUG=True, Django serves static files automatically
|
||||
# But this ensures consistent behavior across all environments
|
||||
|
||||
@@ -12,7 +12,7 @@ import os
|
||||
from .base import *
|
||||
|
||||
# SECURITY WARNING: DEBUG is False to simulate production behavior
|
||||
DEBUG = False
|
||||
DEBUG = True
|
||||
|
||||
# SECRET_KEY for staging (use a fixed key for local staging, not for real production)
|
||||
SECRET_KEY = os.environ.get(
|
||||
@@ -21,9 +21,9 @@ SECRET_KEY = os.environ.get(
|
||||
)
|
||||
|
||||
# Allow localhost for staging
|
||||
ALLOWED_HOSTS = os.environ.get("ALLOWED_HOSTS", "localhost,127.0.0.1,0.0.0.0").split(
|
||||
","
|
||||
)
|
||||
ALLOWED_HOSTS = os.environ.get(
|
||||
"ALLOWED_HOSTS", "localhost,127.0.0.1,0.0.0.0"
|
||||
).split(",")
|
||||
|
||||
# CORS settings for staging - permissive for localhost testing
|
||||
CORS_ALLOWED_ORIGINS = os.environ.get(
|
||||
@@ -52,9 +52,11 @@ CORS_EXPOSE_HEADERS = ["Content-Type", "X-CSRFToken"]
|
||||
DATABASES = {
|
||||
"default": {
|
||||
"ENGINE": "django.db.backends.postgresql",
|
||||
"NAME": os.environ.get("DB_NAME", "tienda_ilusion_staging"),
|
||||
"USER": os.environ.get("DB_USER", "tienda_ilusion_user"),
|
||||
"PASSWORD": os.environ.get("DB_PASSWORD", "staging_local_password"),
|
||||
"NAME": os.environ.get("POSTGRES_DB", "tienda_ilusion_staging"),
|
||||
"USER": os.environ.get("POSTGRES_USER", "tienda_ilusion_user"),
|
||||
"PASSWORD": os.environ.get(
|
||||
"POSTGRES_PASSWORD", "staging_local_password"
|
||||
),
|
||||
"HOST": os.environ.get("DB_HOST", "localhost"),
|
||||
"PORT": os.environ.get("DB_PORT", "5432"),
|
||||
"CONN_MAX_AGE": 600, # Persistent connections
|
||||
@@ -117,7 +119,9 @@ WHITENOISE_AUTOREFRESH = (
|
||||
)
|
||||
WHITENOISE_USE_FINDERS = False # Use collected static files only
|
||||
WHITENOISE_MANIFEST_STRICT = False # More permissive in staging
|
||||
WHITENOISE_MAX_AGE = 600 # 10 minutes cache for staging (allows easier testing)
|
||||
WHITENOISE_MAX_AGE = (
|
||||
600 # 10 minutes cache for staging (allows easier testing)
|
||||
)
|
||||
|
||||
# Staging logging - similar to production but more verbose
|
||||
LOGGING = {
|
||||
@@ -148,7 +152,7 @@ LOGGING = {
|
||||
},
|
||||
"root": {
|
||||
"handlers": ["console", "file"],
|
||||
"level": "INFO",
|
||||
"level": "DEBUG",
|
||||
},
|
||||
"loggers": {
|
||||
"django": {
|
||||
@@ -163,7 +167,7 @@ LOGGING = {
|
||||
},
|
||||
"django.db.backends": {
|
||||
"handlers": ["console"],
|
||||
"level": "INFO", # Show SQL queries in staging for debugging
|
||||
"level": "DEBUG", # Show SQL queries in staging for debugging
|
||||
"propagate": False,
|
||||
},
|
||||
},
|
||||
@@ -177,7 +181,10 @@ pathlib.Path(logs_dir).mkdir(parents=True, exist_ok=True)
|
||||
|
||||
# Admin email notifications
|
||||
ADMINS = [
|
||||
("Staging Admin", os.environ.get("ADMIN_EMAIL", "admin@tiendailusion.local")),
|
||||
(
|
||||
"Staging Admin",
|
||||
os.environ.get("ADMIN_EMAIL", "admin@tiendailusion.local"),
|
||||
),
|
||||
]
|
||||
MANAGERS = ADMINS
|
||||
|
||||
|
||||
@@ -14,6 +14,8 @@ Including another URLconf
|
||||
1. Import the include() function: from django.urls import include, path
|
||||
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
|
||||
"""
|
||||
from django.conf import settings
|
||||
from django.conf.urls.static import static
|
||||
from django.contrib import admin
|
||||
from django.urls import include, path
|
||||
from rest_framework_simplejwt.views import (
|
||||
@@ -32,3 +34,8 @@ urlpatterns = [
|
||||
name='token_refresh'),
|
||||
path('api/users/', include('users.urls')),
|
||||
]
|
||||
|
||||
# Serve media files through Django only in development.
|
||||
# In production/staging, media is served by the web server (nginx).
|
||||
if settings.DEBUG:
|
||||
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
|
||||
|
||||
@@ -10,13 +10,72 @@ from .models.sales import (
|
||||
)
|
||||
from .models.products import Product, ProductCategory
|
||||
from .models.payments import ReconciliationJar
|
||||
from .models.store_settings import StoreSettings
|
||||
|
||||
|
||||
@admin.register(StoreSettings)
|
||||
class StoreSettingsAdmin(admin.ModelAdmin):
|
||||
list_display = ("id", "address", "latitude", "longitude", "updated_at")
|
||||
|
||||
|
||||
@admin.register(Customer)
|
||||
class CustomerAdmin(admin.ModelAdmin):
|
||||
list_display = (
|
||||
"name",
|
||||
"email",
|
||||
"phone",
|
||||
"external_id",
|
||||
"address_external_id",
|
||||
)
|
||||
search_fields = ("name", "email", "phone")
|
||||
|
||||
@admin.register(Sale)
|
||||
class SaleAdmin(admin.ModelAdmin):
|
||||
list_display = (
|
||||
"id",
|
||||
"date",
|
||||
"customer",
|
||||
"payment_method",
|
||||
"external_id",
|
||||
"code",
|
||||
)
|
||||
search_fields = ("date", "customer__name", "payment_method", "external_id", "code")
|
||||
list_filter = ("date", "customer__name", "payment_method")
|
||||
|
||||
@admin.register(SaleLine)
|
||||
class SaleLineAdmin(admin.ModelAdmin):
|
||||
list_display = ("sale", "product", "quantity", "unit_price")
|
||||
search_fields = ("sale__id", "product__name")
|
||||
list_filter = ("sale__date", "product__name")
|
||||
|
||||
@admin.register(CatalogSale)
|
||||
class CatalogSaleAdmin(admin.ModelAdmin):
|
||||
list_display = (
|
||||
"id",
|
||||
"date",
|
||||
"customer_name",
|
||||
"customer_phone",
|
||||
"customer_address",
|
||||
"pickup_method",
|
||||
"external_id",
|
||||
"code",
|
||||
)
|
||||
search_fields = ("date","customer_name", "customer_phone", "pickup_method","external_id", "code")
|
||||
list_filter = ("date", "customer_name", "pickup_method")
|
||||
|
||||
|
||||
@admin.register(CatalogSaleLine)
|
||||
class CatalogSaleLineAdmin(admin.ModelAdmin):
|
||||
list_display = ("catalog_sale", "product", "quantity", "unit_price")
|
||||
search_fields = ("catalog_sale__id", "product__name")
|
||||
list_filter = ("catalog_sale__date", "product__name")
|
||||
|
||||
@admin.register(Product)
|
||||
class ProductAdmin(admin.ModelAdmin):
|
||||
list_display = ("name", "price", "measuring_unit", "external_id")
|
||||
search_fields = ("id", "name",)
|
||||
list_filter = ("name", "id")
|
||||
|
||||
admin.site.register(Customer)
|
||||
admin.site.register(Sale)
|
||||
admin.site.register(SaleLine)
|
||||
admin.site.register(CatalogSale)
|
||||
admin.site.register(CatalogSaleLine)
|
||||
admin.site.register(Product)
|
||||
admin.site.register(ProductCategory)
|
||||
admin.site.register(Payment)
|
||||
admin.site.register(ReconciliationJar)
|
||||
|
||||
52
tienda_ilusion/don_confiao/api/__init__.py
Normal file
52
tienda_ilusion/don_confiao/api/__init__.py
Normal file
@@ -0,0 +1,52 @@
|
||||
from .catalogue_images import CatalogueImageViewSet
|
||||
from .products import ProductView, ProductsFromTrytonView
|
||||
from .customers import CustomerView, CustomersFromTrytonView
|
||||
from .sales import (
|
||||
SaleView,
|
||||
CatalogSaleView,
|
||||
SaleSummary,
|
||||
CatalogSaleSummary,
|
||||
PublicSaleSummaryView,
|
||||
SalesForTrytonView,
|
||||
SalesToTrytonView,
|
||||
CatalogSalesToTrytonView,
|
||||
)
|
||||
from .payments import (
|
||||
ReconciliateJarView,
|
||||
ReconciliateJarModelView,
|
||||
PaymentMethodView,
|
||||
SalesForReconciliationView,
|
||||
Pagination,
|
||||
)
|
||||
from .admin import AdminCodeValidateView
|
||||
from .store_settings import StoreSettingsView
|
||||
|
||||
__all__ = [
|
||||
# Catalogue Images
|
||||
"CatalogueImageViewSet",
|
||||
# Products
|
||||
"ProductView",
|
||||
"ProductsFromTrytonView",
|
||||
# Customers
|
||||
"CustomerView",
|
||||
"CustomersFromTrytonView",
|
||||
# Sales
|
||||
"SaleView",
|
||||
"CatalogSaleView",
|
||||
"SaleSummary",
|
||||
"CatalogSaleSummary",
|
||||
"PublicSaleSummaryView",
|
||||
"SalesForTrytonView",
|
||||
"SalesToTrytonView",
|
||||
"CatalogSalesToTrytonView",
|
||||
# Payments
|
||||
"ReconciliateJarView",
|
||||
"ReconciliateJarModelView",
|
||||
"PaymentMethodView",
|
||||
"SalesForReconciliationView",
|
||||
"Pagination",
|
||||
# Admin
|
||||
"AdminCodeValidateView",
|
||||
# Store Settings
|
||||
"StoreSettingsView",
|
||||
]
|
||||
14
tienda_ilusion/don_confiao/api/admin.py
Normal file
14
tienda_ilusion/don_confiao/api/admin.py
Normal file
@@ -0,0 +1,14 @@
|
||||
from rest_framework.views import APIView
|
||||
from rest_framework.response import Response
|
||||
from rest_framework.permissions import IsAuthenticated
|
||||
|
||||
from ..models.admin import AdminCode
|
||||
from ..permissions import IsAdministrator
|
||||
|
||||
|
||||
class AdminCodeValidateView(APIView):
|
||||
permission_classes = [IsAuthenticated, IsAdministrator]
|
||||
|
||||
def get(self, request, code):
|
||||
codes = AdminCode.objects.filter(value=code)
|
||||
return Response({"validCode": bool(codes)})
|
||||
25
tienda_ilusion/don_confiao/api/catalogue_images.py
Normal file
25
tienda_ilusion/don_confiao/api/catalogue_images.py
Normal file
@@ -0,0 +1,25 @@
|
||||
from rest_framework import viewsets
|
||||
from rest_framework.permissions import AllowAny, IsAuthenticated
|
||||
|
||||
from ..image_service import resize_catalogue_image
|
||||
from ..models.catalogue_images import CatalogueImage
|
||||
from ..permissions import IsAdministrator
|
||||
from ..serializers.catalogue_images import CatalogueImageSerializer
|
||||
|
||||
|
||||
class CatalogueImageViewSet(viewsets.ModelViewSet):
|
||||
queryset = CatalogueImage.objects.all()
|
||||
serializer_class = CatalogueImageSerializer
|
||||
|
||||
def get_permissions(self):
|
||||
if self.action in ("create", "update", "partial_update", "destroy"):
|
||||
return [IsAuthenticated(), IsAdministrator()]
|
||||
return [AllowAny()]
|
||||
|
||||
def perform_create(self, serializer):
|
||||
instance = serializer.save()
|
||||
resize_catalogue_image(instance.image)
|
||||
|
||||
def perform_update(self, serializer):
|
||||
instance = serializer.save()
|
||||
resize_catalogue_image(instance.image)
|
||||
26
tienda_ilusion/don_confiao/api/customers.py
Normal file
26
tienda_ilusion/don_confiao/api/customers.py
Normal file
@@ -0,0 +1,26 @@
|
||||
from rest_framework import viewsets
|
||||
from rest_framework.views import APIView
|
||||
from rest_framework.response import Response
|
||||
from rest_framework.permissions import IsAuthenticated
|
||||
|
||||
from ..models.customers import Customer
|
||||
from ..serializers import CustomerSerializer
|
||||
from ..permissions import IsAdministrator, IsNotPublico
|
||||
from ..services.tryton.customers import CustomerTrytonService
|
||||
from ..services.tryton.client import get_tryton_client
|
||||
|
||||
|
||||
class CustomerView(viewsets.ModelViewSet):
|
||||
queryset = Customer.objects.all()
|
||||
serializer_class = CustomerSerializer
|
||||
permission_classes = [IsNotPublico]
|
||||
|
||||
|
||||
class CustomersFromTrytonView(APIView):
|
||||
permission_classes = [IsAuthenticated, IsAdministrator]
|
||||
|
||||
def post(self, request):
|
||||
tryton_client = get_tryton_client()
|
||||
service = CustomerTrytonService(tryton_client)
|
||||
result = service.import_from_tryton()
|
||||
return Response(result, status=200)
|
||||
110
tienda_ilusion/don_confiao/api/payments.py
Normal file
110
tienda_ilusion/don_confiao/api/payments.py
Normal file
@@ -0,0 +1,110 @@
|
||||
from rest_framework import viewsets
|
||||
from rest_framework.views import APIView
|
||||
from rest_framework.response import Response
|
||||
from rest_framework.status import HTTP_400_BAD_REQUEST
|
||||
from rest_framework.pagination import PageNumberPagination
|
||||
from rest_framework.permissions import AllowAny, IsAuthenticated
|
||||
from decimal import Decimal
|
||||
|
||||
from ..models.sales import Sale
|
||||
from ..models.payments import ReconciliationJar, PaymentMethods
|
||||
from ..serializers import (
|
||||
ReconciliationJarSerializer,
|
||||
PaymentMethodSerializer,
|
||||
SaleForRenconciliationSerializer,
|
||||
)
|
||||
from ..permissions import IsAdministrator
|
||||
|
||||
|
||||
class Pagination(PageNumberPagination):
|
||||
page_size = 10
|
||||
page_size_query_param = "page_size"
|
||||
|
||||
|
||||
class ReconciliateJarView(APIView):
|
||||
permission_classes = [IsAuthenticated, IsAdministrator]
|
||||
|
||||
def post(self, request):
|
||||
data = request.data
|
||||
cash_purchases_id = data.get("cash_purchases")
|
||||
serializer = ReconciliationJarSerializer(data=data)
|
||||
if serializer.is_valid():
|
||||
cash_purchases = Sale.objects.filter(pk__in=cash_purchases_id)
|
||||
if not self._is_valid_total(
|
||||
cash_purchases, data.get("total_cash_purchases")
|
||||
):
|
||||
return Response(
|
||||
{
|
||||
"error": "total_cash_purchases not equal to sum of all purchases."
|
||||
},
|
||||
status=HTTP_400_BAD_REQUEST,
|
||||
)
|
||||
reconciliation = serializer.save()
|
||||
other_purchases = self._get_other_purchases(data.get("other_totals"))
|
||||
|
||||
self._link_purchases(reconciliation, cash_purchases, other_purchases)
|
||||
return Response({"id": reconciliation.id})
|
||||
return Response(serializer.errors, status=HTTP_400_BAD_REQUEST)
|
||||
|
||||
def get(self, request):
|
||||
reconciliations = ReconciliationJar.objects.all()
|
||||
serializer = ReconciliationJarSerializer(reconciliations, many=True)
|
||||
return Response(serializer.data)
|
||||
|
||||
def _is_valid_total(self, purchases, total):
|
||||
calculated_total = sum(p.get_total() for p in purchases)
|
||||
return Decimal(calculated_total).quantize(Decimal(".0001")) == (
|
||||
Decimal(total).quantize(Decimal(".0001"))
|
||||
)
|
||||
|
||||
def _get_other_purchases(self, other_totals):
|
||||
if not other_totals:
|
||||
return []
|
||||
purchases = []
|
||||
for method in other_totals:
|
||||
purchases.extend(other_totals[method]["purchases"])
|
||||
if purchases:
|
||||
return Sale.objects.filter(pk__in=purchases)
|
||||
return []
|
||||
|
||||
def _link_purchases(self, reconciliation, cash_purchases, other_purchases):
|
||||
for purchase in cash_purchases:
|
||||
purchase.reconciliation = reconciliation
|
||||
purchase.clean()
|
||||
purchase.save()
|
||||
|
||||
for purchase in other_purchases:
|
||||
purchase.reconciliation = reconciliation
|
||||
purchase.clean()
|
||||
purchase.save()
|
||||
|
||||
|
||||
class ReconciliateJarModelView(viewsets.ModelViewSet):
|
||||
queryset = ReconciliationJar.objects.all().order_by("-date_time")
|
||||
pagination_class = Pagination
|
||||
serializer_class = ReconciliationJarSerializer
|
||||
permission_classes = [IsAuthenticated, IsAdministrator]
|
||||
|
||||
|
||||
class PaymentMethodView(APIView):
|
||||
permission_classes = [AllowAny]
|
||||
|
||||
def get(self, request):
|
||||
serializer = PaymentMethodSerializer(PaymentMethods.choices, many=True)
|
||||
return Response(serializer.data)
|
||||
|
||||
|
||||
class SalesForReconciliationView(APIView):
|
||||
permission_classes = [IsAuthenticated, IsAdministrator]
|
||||
|
||||
def get(self, request):
|
||||
sales = Sale.objects.filter(reconciliation=None)
|
||||
grouped_sales = {}
|
||||
|
||||
for sale in sales:
|
||||
if sale.payment_method not in grouped_sales.keys():
|
||||
grouped_sales[sale.payment_method] = []
|
||||
serializer = SaleForRenconciliationSerializer(sale)
|
||||
grouped_sales[sale.payment_method].append(serializer.data)
|
||||
|
||||
return Response(grouped_sales)
|
||||
58
tienda_ilusion/don_confiao/api/products.py
Normal file
58
tienda_ilusion/don_confiao/api/products.py
Normal file
@@ -0,0 +1,58 @@
|
||||
from rest_framework import viewsets
|
||||
from rest_framework.views import APIView
|
||||
from rest_framework.response import Response
|
||||
from rest_framework.permissions import AllowAny, IsAuthenticated
|
||||
|
||||
from ..models.products import Product
|
||||
from ..serializers import ProductSerializer
|
||||
from ..permissions import IsAdministrator, IsNotPublico
|
||||
from ..services.tryton.products import ProductTrytonService
|
||||
from ..services.tryton.client import get_tryton_client
|
||||
|
||||
|
||||
class ProductView(viewsets.ModelViewSet):
|
||||
queryset = Product.objects.all()
|
||||
serializer_class = ProductSerializer
|
||||
|
||||
def get_permissions(self):
|
||||
if self.action in ("list", "retrieve"):
|
||||
return [AllowAny()]
|
||||
return [IsNotPublico()]
|
||||
|
||||
def get_queryset(self):
|
||||
"""
|
||||
Filters products by active status for list operations.
|
||||
Detail operations (retrieve, update, destroy) return all products.
|
||||
|
||||
Query params for list:
|
||||
- active=true (default): Only active products
|
||||
- active=false: Only inactive products
|
||||
- active=all: All products regardless of status
|
||||
"""
|
||||
queryset = Product.objects.all()
|
||||
|
||||
# Only filter for list action, not for detail operations
|
||||
if self.action != "list":
|
||||
return queryset
|
||||
|
||||
active_param = self.request.query_params.get("active", "true")
|
||||
|
||||
if active_param.lower() == "all":
|
||||
return queryset
|
||||
elif active_param.lower() in ["true", "1", "yes"]:
|
||||
return queryset.filter(active=True)
|
||||
elif active_param.lower() in ["false", "0", "no"]:
|
||||
return queryset.filter(active=False)
|
||||
else:
|
||||
# Default behavior: return only active products
|
||||
return queryset.filter(active=True)
|
||||
|
||||
|
||||
class ProductsFromTrytonView(APIView):
|
||||
permission_classes = [IsAuthenticated, IsAdministrator]
|
||||
|
||||
def post(self, request):
|
||||
tryton_client = get_tryton_client()
|
||||
service = ProductTrytonService(tryton_client)
|
||||
result = service.import_from_tryton()
|
||||
return Response(result, status=200)
|
||||
191
tienda_ilusion/don_confiao/api/sales.py
Normal file
191
tienda_ilusion/don_confiao/api/sales.py
Normal file
@@ -0,0 +1,191 @@
|
||||
from rest_framework import viewsets
|
||||
from rest_framework.views import APIView
|
||||
from rest_framework.response import Response
|
||||
from rest_framework.permissions import AllowAny, IsAuthenticated
|
||||
from rest_framework.decorators import action
|
||||
import io
|
||||
import csv
|
||||
|
||||
from ..models.sales import (
|
||||
Sale,
|
||||
SaleLine,
|
||||
CatalogSale,
|
||||
generate_order_code,
|
||||
)
|
||||
from ..models.customers import Customer
|
||||
from ..models.products import Product
|
||||
from ..serializers import (
|
||||
SaleSerializer,
|
||||
CatalogSaleSerializer,
|
||||
SaleSummarySerializer,
|
||||
CatalogSaleSummarySerializer,
|
||||
)
|
||||
from ..permissions import IsAdministrator, IsNotPublico
|
||||
from ..services.tryton.sales import SaleTrytonService
|
||||
from ..services.tryton.client import get_tryton_client
|
||||
from ..views import sales_to_tryton_csv
|
||||
|
||||
|
||||
def _fill_codes(Model):
|
||||
rows = Model.objects.all()
|
||||
for row in rows:
|
||||
row.code = generate_order_code()
|
||||
Model.objects.bulk_update(rows, ["code"])
|
||||
return len(rows)
|
||||
|
||||
|
||||
class SaleView(viewsets.ModelViewSet):
|
||||
queryset = Sale.objects.all()
|
||||
serializer_class = SaleSerializer
|
||||
permission_classes = [IsNotPublico]
|
||||
|
||||
@action(
|
||||
detail=False,
|
||||
methods=["post"],
|
||||
permission_classes=[IsAuthenticated, IsAdministrator],
|
||||
)
|
||||
def fill_codes(self, request):
|
||||
return Response({"sales_updated": _fill_codes(Sale)})
|
||||
|
||||
def create(self, request):
|
||||
data = request.data
|
||||
customer = Customer.objects.get(pk=data["customer"])
|
||||
date = data["date"]
|
||||
lines = data["saleline_set"]
|
||||
payment_method = data["payment_method"]
|
||||
description = data.get("notes", "")
|
||||
sale = Sale.objects.create(
|
||||
customer=customer,
|
||||
date=date,
|
||||
payment_method=payment_method,
|
||||
description=description,
|
||||
)
|
||||
|
||||
for line in lines:
|
||||
product = Product.objects.get(pk=line["product"])
|
||||
quantity = line["quantity"]
|
||||
unit_price = line["unit_price"]
|
||||
SaleLine.objects.create(
|
||||
sale=sale,
|
||||
product=product,
|
||||
quantity=quantity,
|
||||
unit_price=unit_price,
|
||||
)
|
||||
|
||||
return Response(
|
||||
{"id": sale.id, "message": "Venta creada con exito"},
|
||||
status=201,
|
||||
)
|
||||
|
||||
|
||||
class CatalogSaleView(viewsets.ModelViewSet):
|
||||
queryset = CatalogSale.objects.all()
|
||||
serializer_class = CatalogSaleSerializer
|
||||
|
||||
@action(
|
||||
detail=False,
|
||||
methods=["post"],
|
||||
permission_classes=[IsAuthenticated, IsAdministrator],
|
||||
)
|
||||
def fill_codes(self, request):
|
||||
return Response({"catalog_sales_updated": _fill_codes(CatalogSale)})
|
||||
|
||||
def get_permissions(self):
|
||||
if self.action == "fill_codes":
|
||||
return [IsAuthenticated(), IsAdministrator()]
|
||||
if self.action == "create":
|
||||
return [IsAuthenticated()]
|
||||
return [IsNotPublico()]
|
||||
|
||||
|
||||
class SaleSummary(APIView):
|
||||
permission_classes = [IsNotPublico]
|
||||
|
||||
def get(self, request, id):
|
||||
sale = Sale.objects.get(pk=id)
|
||||
serializer = SaleSummarySerializer(
|
||||
sale, context={"request": request}
|
||||
)
|
||||
return Response(serializer.data)
|
||||
|
||||
|
||||
class CatalogSaleSummary(APIView):
|
||||
permission_classes = [IsAuthenticated]
|
||||
|
||||
def get(self, request, id):
|
||||
catalog_sale = CatalogSale.objects.get(pk=id)
|
||||
serializer = CatalogSaleSummarySerializer(
|
||||
catalog_sale, context={"request": request}
|
||||
)
|
||||
return Response(serializer.data)
|
||||
|
||||
|
||||
class PublicSaleSummaryView(APIView):
|
||||
permission_classes = [AllowAny]
|
||||
|
||||
def get(self, request, code=None):
|
||||
code = code or request.query_params.get("code")
|
||||
if not code:
|
||||
return Response(
|
||||
{"detail": "code is required"}, status=400
|
||||
)
|
||||
|
||||
sale = Sale.objects.filter(code=code).first()
|
||||
if sale:
|
||||
serializer = SaleSummarySerializer(
|
||||
sale, context={"request": request}
|
||||
)
|
||||
data = serializer.data
|
||||
data["type"] = "sale"
|
||||
return Response(data)
|
||||
|
||||
catalog_sale = CatalogSale.objects.filter(code=code).first()
|
||||
if catalog_sale:
|
||||
serializer = CatalogSaleSummarySerializer(
|
||||
catalog_sale, context={"request": request}
|
||||
)
|
||||
data = serializer.data
|
||||
data["type"] = "catalog"
|
||||
return Response(data)
|
||||
|
||||
return Response(
|
||||
{"detail": "order not found"}, status=404
|
||||
)
|
||||
|
||||
|
||||
class SalesForTrytonView(APIView):
|
||||
permission_classes = [IsAuthenticated, IsAdministrator]
|
||||
|
||||
def get(self, request):
|
||||
sales = Sale.objects.all()
|
||||
csv_data = self._generate_sales_CSV(sales)
|
||||
return Response({"csv": csv_data})
|
||||
|
||||
def _generate_sales_CSV(self, sales):
|
||||
output = io.StringIO()
|
||||
writer = csv.writer(output)
|
||||
csv_data = sales_to_tryton_csv(sales)
|
||||
|
||||
for row in csv_data:
|
||||
writer.writerow(row)
|
||||
return output.getvalue()
|
||||
|
||||
|
||||
class SalesToTrytonView(APIView):
|
||||
permission_classes = [IsAuthenticated, IsAdministrator]
|
||||
|
||||
def post(self, request):
|
||||
tryton_client = get_tryton_client()
|
||||
service = SaleTrytonService(tryton_client)
|
||||
result = service.send_to_tryton()
|
||||
return Response(result, status=200)
|
||||
|
||||
|
||||
class CatalogSalesToTrytonView(APIView):
|
||||
permission_classes = [IsAuthenticated, IsAdministrator]
|
||||
|
||||
def post(self, request):
|
||||
tryton_client = get_tryton_client()
|
||||
service = SaleTrytonService(tryton_client)
|
||||
result = service.send_catalog_sales_to_tryton()
|
||||
return Response(result, status=200)
|
||||
32
tienda_ilusion/don_confiao/api/store_settings.py
Normal file
32
tienda_ilusion/don_confiao/api/store_settings.py
Normal file
@@ -0,0 +1,32 @@
|
||||
from rest_framework import status
|
||||
from rest_framework.permissions import AllowAny, IsAuthenticated
|
||||
from rest_framework.response import Response
|
||||
from rest_framework.views import APIView
|
||||
|
||||
from ..models.store_settings import StoreSettings
|
||||
from ..permissions import IsAdministrator
|
||||
from ..serializers.store_settings import StoreSettingsSerializer
|
||||
|
||||
|
||||
class StoreSettingsView(APIView):
|
||||
def get_permissions(self):
|
||||
if self.request.method == "GET":
|
||||
return [AllowAny()]
|
||||
return [IsAuthenticated(), IsAdministrator()]
|
||||
|
||||
def get(self, request):
|
||||
settings = StoreSettings.get_singleton()
|
||||
return Response(
|
||||
StoreSettingsSerializer(
|
||||
settings, context={"request": request}
|
||||
).data
|
||||
)
|
||||
|
||||
def patch(self, request):
|
||||
settings = StoreSettings.get_singleton()
|
||||
serializer = StoreSettingsSerializer(
|
||||
settings, data=request.data, partial=True, context={"request": request}
|
||||
)
|
||||
serializer.is_valid(raise_exception=True)
|
||||
serializer.save()
|
||||
return Response(serializer.data, status=status.HTTP_200_OK)
|
||||
@@ -1,525 +0,0 @@
|
||||
from rest_framework import viewsets
|
||||
from rest_framework.response import Response
|
||||
from rest_framework.status import HTTP_400_BAD_REQUEST
|
||||
from rest_framework.views import APIView
|
||||
from rest_framework.pagination import PageNumberPagination
|
||||
from rest_framework.permissions import IsAuthenticated
|
||||
|
||||
from .models.sales import Sale, SaleLine
|
||||
from .models.customers import Customer
|
||||
from .models.sales import (
|
||||
Sale,
|
||||
SaleLine,
|
||||
CatalogSale,
|
||||
CatalogSaleLine,
|
||||
Payment,
|
||||
)
|
||||
from .models.products import Product, ProductCategory
|
||||
from .models.payments import PaymentMethods, ReconciliationJar
|
||||
from .models.admin import AdminCode
|
||||
|
||||
from .serializers import (
|
||||
SaleSerializer,
|
||||
CatalogSaleSerializer,
|
||||
ProductSerializer,
|
||||
CustomerSerializer,
|
||||
ReconciliationJarSerializer,
|
||||
PaymentMethodSerializer,
|
||||
SaleForRenconciliationSerializer,
|
||||
SaleSummarySerializer,
|
||||
)
|
||||
from .views import sales_to_tryton_csv
|
||||
from .permissions import IsAdministrator
|
||||
|
||||
from decimal import Decimal
|
||||
from sabatron_tryton_rpc_client.client import Client
|
||||
import io
|
||||
import csv
|
||||
import os
|
||||
|
||||
TRYTON_HOST = os.environ.get("TRYTON_HOST", "localhost")
|
||||
TRYTON_DATABASE = os.environ.get("TRYTON_DATABASE", "tryton")
|
||||
TRYTON_USERNAME = os.environ.get("TRYTON_USERNAME", "admin")
|
||||
TRYTON_PASSWORD = os.environ.get("TRYTON_PASSWORD", "admin")
|
||||
TRYTON_COP_CURRENCY = 31
|
||||
TRYTON_COMPANY_ID = 1
|
||||
TRYTON_SHOPS = [1]
|
||||
|
||||
|
||||
class Pagination(PageNumberPagination):
|
||||
page_size = 10
|
||||
page_size_query_param = "page_size"
|
||||
|
||||
|
||||
class SaleView(viewsets.ModelViewSet):
|
||||
queryset = Sale.objects.all()
|
||||
serializer_class = SaleSerializer
|
||||
|
||||
def create(self, request):
|
||||
data = request.data
|
||||
customer = Customer.objects.get(pk=data["customer"])
|
||||
date = data["date"]
|
||||
lines = data["saleline_set"]
|
||||
payment_method = data["payment_method"]
|
||||
description = data.get("notes", "")
|
||||
sale = Sale.objects.create(
|
||||
customer=customer,
|
||||
date=date,
|
||||
payment_method=payment_method,
|
||||
description=description,
|
||||
)
|
||||
|
||||
for line in lines:
|
||||
product = Product.objects.get(pk=line["product"])
|
||||
quantity = line["quantity"]
|
||||
unit_price = line["unit_price"]
|
||||
SaleLine.objects.create(
|
||||
sale=sale,
|
||||
product=product,
|
||||
quantity=quantity,
|
||||
unit_price=unit_price,
|
||||
)
|
||||
|
||||
return Response(
|
||||
{"id": sale.id, "message": "Venta creada con exito"},
|
||||
status=201,
|
||||
)
|
||||
|
||||
|
||||
class CatalogSaleView(viewsets.ModelViewSet):
|
||||
queryset = CatalogSale.objects.all()
|
||||
serializer_class = CatalogSaleSerializer
|
||||
|
||||
|
||||
class ProductView(viewsets.ModelViewSet):
|
||||
queryset = Product.objects.all()
|
||||
serializer_class = ProductSerializer
|
||||
|
||||
def get_queryset(self):
|
||||
"""
|
||||
Filters products by active status for list operations.
|
||||
Detail operations (retrieve, update, destroy) return all products.
|
||||
|
||||
Query params for list:
|
||||
- active=true (default): Only active products
|
||||
- active=false: Only inactive products
|
||||
- active=all: All products regardless of status
|
||||
"""
|
||||
queryset = Product.objects.all()
|
||||
|
||||
# Only filter for list action, not for detail operations
|
||||
if self.action != "list":
|
||||
return queryset
|
||||
|
||||
active_param = self.request.query_params.get("active", "true")
|
||||
|
||||
if active_param.lower() == "all":
|
||||
return queryset
|
||||
elif active_param.lower() in ["true", "1", "yes"]:
|
||||
return queryset.filter(active=True)
|
||||
elif active_param.lower() in ["false", "0", "no"]:
|
||||
return queryset.filter(active=False)
|
||||
else:
|
||||
# Default behavior: return only active products
|
||||
return queryset.filter(active=True)
|
||||
|
||||
|
||||
class CustomerView(viewsets.ModelViewSet):
|
||||
queryset = Customer.objects.all()
|
||||
serializer_class = CustomerSerializer
|
||||
|
||||
|
||||
class ReconciliateJarView(APIView):
|
||||
permission_classes = [IsAuthenticated, IsAdministrator]
|
||||
|
||||
def post(self, request):
|
||||
data = request.data
|
||||
cash_purchases_id = data.get("cash_purchases")
|
||||
serializer = ReconciliationJarSerializer(data=data)
|
||||
if serializer.is_valid():
|
||||
cash_purchases = Sale.objects.filter(pk__in=cash_purchases_id)
|
||||
if not self._is_valid_total(
|
||||
cash_purchases, data.get("total_cash_purchases")
|
||||
):
|
||||
return Response(
|
||||
{
|
||||
"error": "total_cash_purchases not equal to sum of all purchases."
|
||||
},
|
||||
status=HTTP_400_BAD_REQUEST,
|
||||
)
|
||||
reconciliation = serializer.save()
|
||||
other_purchases = self._get_other_purchases(data.get("other_totals"))
|
||||
|
||||
self._link_purchases(reconciliation, cash_purchases, other_purchases)
|
||||
return Response({"id": reconciliation.id})
|
||||
return Response(serializer.errors, status=HTTP_400_BAD_REQUEST)
|
||||
|
||||
def get(self, request):
|
||||
reconciliations = ReconciliationJar.objects.all()
|
||||
serializer = ReconciliationJarSerializer(reconciliations, many=True)
|
||||
return Response(serializer.data)
|
||||
|
||||
def _is_valid_total(self, purchases, total):
|
||||
calculated_total = sum(p.get_total() for p in purchases)
|
||||
return Decimal(calculated_total).quantize(Decimal(".0001")) == (
|
||||
Decimal(total).quantize(Decimal(".0001"))
|
||||
)
|
||||
|
||||
def _get_other_purchases(self, other_totals):
|
||||
if not other_totals:
|
||||
return []
|
||||
purchases = []
|
||||
for method in other_totals:
|
||||
purchases.extend(other_totals[method]["purchases"])
|
||||
if purchases:
|
||||
return Sale.objects.filter(pk__in=purchases)
|
||||
return []
|
||||
|
||||
def _link_purchases(self, reconciliation, cash_purchases, other_purchases):
|
||||
for purchase in cash_purchases:
|
||||
purchase.reconciliation = reconciliation
|
||||
purchase.clean()
|
||||
purchase.save()
|
||||
|
||||
for purchase in other_purchases:
|
||||
purchase.reconciliation = reconciliation
|
||||
purchase.clean()
|
||||
purchase.save()
|
||||
|
||||
|
||||
class PaymentMethodView(APIView):
|
||||
def get(self, request):
|
||||
serializer = PaymentMethodSerializer(PaymentMethods.choices, many=True)
|
||||
return Response(serializer.data)
|
||||
|
||||
|
||||
class SalesForReconciliationView(APIView):
|
||||
permission_classes = [IsAuthenticated, IsAdministrator]
|
||||
|
||||
def get(self, request):
|
||||
sales = Sale.objects.filter(reconciliation=None)
|
||||
grouped_sales = {}
|
||||
|
||||
for sale in sales:
|
||||
if sale.payment_method not in grouped_sales.keys():
|
||||
grouped_sales[sale.payment_method] = []
|
||||
serializer = SaleForRenconciliationSerializer(sale)
|
||||
grouped_sales[sale.payment_method].append(serializer.data)
|
||||
|
||||
return Response(grouped_sales)
|
||||
|
||||
|
||||
class SaleSummary(APIView):
|
||||
def get(self, request, id):
|
||||
sale = Sale.objects.get(pk=id)
|
||||
serializer = SaleSummarySerializer(sale)
|
||||
return Response(serializer.data)
|
||||
|
||||
|
||||
class AdminCodeValidateView(APIView):
|
||||
permission_classes = [IsAuthenticated, IsAdministrator]
|
||||
|
||||
def get(self, request, code):
|
||||
codes = AdminCode.objects.filter(value=code)
|
||||
return Response({"validCode": bool(codes)})
|
||||
|
||||
|
||||
class ReconciliateJarModelView(viewsets.ModelViewSet):
|
||||
queryset = ReconciliationJar.objects.all().order_by("-date_time")
|
||||
pagination_class = Pagination
|
||||
serializer_class = ReconciliationJarSerializer
|
||||
permission_classes = [IsAuthenticated, IsAdministrator]
|
||||
|
||||
|
||||
class SalesForTrytonView(APIView):
|
||||
permission_classes = [IsAuthenticated, IsAdministrator]
|
||||
|
||||
def get(self, request):
|
||||
sales = Sale.objects.all()
|
||||
csv = self._generate_sales_CSV(sales)
|
||||
return Response({"csv": csv})
|
||||
|
||||
def _generate_sales_CSV(self, sales):
|
||||
output = io.StringIO()
|
||||
writer = csv.writer(output)
|
||||
csv_data = sales_to_tryton_csv(sales)
|
||||
|
||||
for row in csv_data:
|
||||
writer.writerow(row)
|
||||
return output.getvalue()
|
||||
|
||||
|
||||
class SalesToTrytonView(APIView):
|
||||
permission_classes = [IsAuthenticated, IsAdministrator]
|
||||
|
||||
def post(self, request):
|
||||
tryton_client = Client(
|
||||
hostname=TRYTON_HOST,
|
||||
database=TRYTON_DATABASE,
|
||||
username=TRYTON_USERNAME,
|
||||
password=TRYTON_PASSWORD,
|
||||
)
|
||||
tryton_client.connect()
|
||||
method = "model.sale.sale.create"
|
||||
tryton_context = {
|
||||
"company": TRYTON_COMPANY_ID,
|
||||
"shops": TRYTON_SHOPS,
|
||||
}
|
||||
|
||||
successful = []
|
||||
failed = []
|
||||
|
||||
sales = Sale.objects.filter(external_id=None)
|
||||
for sale in sales:
|
||||
try:
|
||||
lines = SaleLine.objects.filter(sale=sale.id)
|
||||
tryton_params = self.__to_tryton_params(sale, lines, tryton_context)
|
||||
external_ids = tryton_client.call(method, tryton_params)
|
||||
sale.external_id = external_ids[0]
|
||||
sale.save()
|
||||
successful.append(sale.id)
|
||||
except Exception as e:
|
||||
print(f"Error al enviar la venta: {e}venta_id: {sale.id}")
|
||||
failed.append(sale.id)
|
||||
continue
|
||||
|
||||
return Response({"successful": successful, "failed": failed}, status=200)
|
||||
|
||||
def __to_tryton_params(self, sale, lines, tryton_context):
|
||||
sale_tryton = TrytonSale(sale, lines)
|
||||
return [[sale_tryton.to_tryton()], tryton_context]
|
||||
|
||||
|
||||
class TrytonSale:
|
||||
def __init__(self, sale, lines):
|
||||
self.sale = sale
|
||||
self.lines = lines
|
||||
|
||||
def _format_date(self, _date):
|
||||
return {
|
||||
"__class__": "date",
|
||||
"year": _date.year,
|
||||
"month": _date.month,
|
||||
"day": _date.day,
|
||||
}
|
||||
|
||||
def to_tryton(self):
|
||||
return {
|
||||
"company": TRYTON_COMPANY_ID,
|
||||
"shipment_address": self.sale.customer.address_external_id,
|
||||
"invoice_address": self.sale.customer.address_external_id,
|
||||
"currency": TRYTON_COP_CURRENCY,
|
||||
"comment": self.sale.description or "",
|
||||
"description": "Metodo pago: " + str(self.sale.payment_method or ""),
|
||||
"party": self.sale.customer.external_id,
|
||||
"reference": "don_confiao " + str(self.sale.id),
|
||||
"sale_date": self._format_date(self.sale.date),
|
||||
"lines": [
|
||||
[
|
||||
"create",
|
||||
[TrytonLineSale(line).to_tryton() for line in self.lines],
|
||||
]
|
||||
],
|
||||
"self_pick_up": True,
|
||||
}
|
||||
|
||||
|
||||
class TrytonLineSale:
|
||||
def __init__(self, sale_line):
|
||||
self.sale_line = sale_line
|
||||
|
||||
def _format_decimal(self, number):
|
||||
return {"__class__": "Decimal", "decimal": str(number)}
|
||||
|
||||
def to_tryton(self):
|
||||
return {
|
||||
"product": self.sale_line.product.external_id,
|
||||
"quantity": self._format_decimal(self.sale_line.quantity),
|
||||
"type": "line",
|
||||
"unit": self.sale_line.product.unit_external_id,
|
||||
"unit_price": self._format_decimal(self.sale_line.unit_price),
|
||||
}
|
||||
|
||||
|
||||
class ProductsFromTrytonView(APIView):
|
||||
permission_classes = [IsAuthenticated, IsAdministrator]
|
||||
|
||||
def post(self, request):
|
||||
tryton_client = Client(
|
||||
hostname=TRYTON_HOST,
|
||||
database=TRYTON_DATABASE,
|
||||
username=TRYTON_USERNAME,
|
||||
password=TRYTON_PASSWORD,
|
||||
)
|
||||
tryton_client.connect()
|
||||
method = "model.product.product.search"
|
||||
context = {"company": 1}
|
||||
params = [
|
||||
[["salable", "=", True]],
|
||||
0,
|
||||
1000,
|
||||
[["rec_name", "ASC"], ["id", None]],
|
||||
context,
|
||||
]
|
||||
product_ids = tryton_client.call(method, params)
|
||||
tryton_products = self.__get_product_datails_from_tryton(
|
||||
product_ids, tryton_client, context
|
||||
)
|
||||
checked_tryton_products = product_ids
|
||||
failed_products = []
|
||||
updated_products = []
|
||||
created_products = []
|
||||
untouched_products = []
|
||||
|
||||
for tryton_product in tryton_products:
|
||||
try:
|
||||
product = Product.objects.get(external_id=tryton_product.get("id"))
|
||||
except Product.DoesNotExist:
|
||||
try:
|
||||
product = self.__create_product(tryton_product)
|
||||
created_products.append(product.id)
|
||||
continue
|
||||
except Exception as e:
|
||||
print(
|
||||
f"Error al importar productos: {e}El producto: {tryton_product}"
|
||||
)
|
||||
failed_products.append(tryton_product.get("id"))
|
||||
continue
|
||||
|
||||
if self.__need_update(product, tryton_product):
|
||||
self.__update_product(product, tryton_product)
|
||||
updated_products.append(product.id)
|
||||
else:
|
||||
untouched_products.append(product.id)
|
||||
|
||||
return Response(
|
||||
{
|
||||
"checked_tryton_products": checked_tryton_products,
|
||||
"failed_products": failed_products,
|
||||
"updated_products": updated_products,
|
||||
"created_products": created_products,
|
||||
"untouched_products": untouched_products,
|
||||
},
|
||||
status=200,
|
||||
)
|
||||
|
||||
def __get_product_datails_from_tryton(self, product_ids, tryton_client, context):
|
||||
tryton_fields = [
|
||||
"id",
|
||||
"name",
|
||||
"default_uom.id",
|
||||
"default_uom.rec_name",
|
||||
"list_price",
|
||||
]
|
||||
method = "model.product.product.read"
|
||||
params = (product_ids, tryton_fields, context)
|
||||
response = tryton_client.call(method, params)
|
||||
return response
|
||||
|
||||
def __need_update(self, product, tryton_product):
|
||||
if not product.name == tryton_product.get("name"):
|
||||
return True
|
||||
if not product.price == tryton_product.get("list_price"):
|
||||
return True
|
||||
unit = tryton_product.get("default_uom.")
|
||||
if not product.measuring_unit == unit.get("rec_name"):
|
||||
return True
|
||||
|
||||
def __create_product(self, tryton_product):
|
||||
product = Product()
|
||||
product.name = tryton_product.get("name")
|
||||
product.price = tryton_product.get("list_price")
|
||||
product.external_id = tryton_product.get("id")
|
||||
unit = tryton_product.get("default_uom.")
|
||||
product.measuring_unit = unit.get("rec_name")
|
||||
product.unit_external_id = unit.get("id")
|
||||
product.save()
|
||||
return product
|
||||
|
||||
def __update_product(self, product, tryton_product):
|
||||
product.name = tryton_product.get("name")
|
||||
product.price = tryton_product.get("list_price")
|
||||
product.external_id = tryton_product.get("id")
|
||||
unit = tryton_product.get("default_uom.")
|
||||
product.measuring_unit = unit.get("rec_name")
|
||||
product.unit_external_id = unit.get("id")
|
||||
product.save()
|
||||
|
||||
|
||||
class CustomersFromTrytonView(APIView):
|
||||
permission_classes = [IsAuthenticated, IsAdministrator]
|
||||
|
||||
def post(self, request):
|
||||
tryton_client = Client(
|
||||
hostname=TRYTON_HOST,
|
||||
database=TRYTON_DATABASE,
|
||||
username=TRYTON_USERNAME,
|
||||
password=TRYTON_PASSWORD,
|
||||
)
|
||||
tryton_client.connect()
|
||||
method = "model.party.party.search"
|
||||
context = {"company": 1}
|
||||
params = [[], 0, 1000, [["name", "ASC"], ["id", None]], context]
|
||||
party_ids = tryton_client.call(method, params)
|
||||
tryton_parties = self.__get_party_datails(party_ids, tryton_client, context)
|
||||
checked_tryton_parties = party_ids
|
||||
failed_parties = []
|
||||
updated_customers = []
|
||||
created_customers = []
|
||||
untouched_customers = []
|
||||
|
||||
for tryton_party in tryton_parties:
|
||||
try:
|
||||
customer = Customer.objects.get(external_id=tryton_party.get("id"))
|
||||
except Customer.DoesNotExist:
|
||||
customer = self.__create_customer(tryton_party)
|
||||
created_customers.append(customer.id)
|
||||
continue
|
||||
if self.__need_update(customer, tryton_party):
|
||||
self.__update_customer(customer, tryton_party)
|
||||
updated_customers.append(customer.id)
|
||||
else:
|
||||
untouched_customers.append(customer.id)
|
||||
|
||||
return Response(
|
||||
{
|
||||
"checked_tryton_parties": checked_tryton_parties,
|
||||
"failed_parties": failed_parties,
|
||||
"updated_customers": updated_customers,
|
||||
"created_customers": created_customers,
|
||||
"untouched_customers": untouched_customers,
|
||||
},
|
||||
status=200,
|
||||
)
|
||||
|
||||
def __get_party_datails(self, party_ids, tryton_client, context):
|
||||
tryton_fields = ["id", "name", "addresses"]
|
||||
method = "model.party.party.read"
|
||||
params = (party_ids, tryton_fields, context)
|
||||
response = tryton_client.call(method, params)
|
||||
return response
|
||||
|
||||
def __need_update(self, customer, tryton_party):
|
||||
if not customer.name == tryton_party.get("name"):
|
||||
return True
|
||||
if tryton_party.get("addresses") and tryton_party.get("addresses")[0]:
|
||||
if not customer.address_external_id == str(
|
||||
tryton_party.get("addresses")[0]
|
||||
):
|
||||
return True
|
||||
|
||||
def __create_customer(self, tryton_party):
|
||||
customer = Customer()
|
||||
customer.name = tryton_party.get("name")
|
||||
customer.external_id = tryton_party.get("id")
|
||||
if tryton_party.get("addresses") and tryton_party.get("addresses")[0]:
|
||||
customer.address_external_id = tryton_party.get("addresses")[0]
|
||||
customer.save()
|
||||
return customer
|
||||
|
||||
def __update_customer(self, customer, tryton_party):
|
||||
customer.name = tryton_party.get("name")
|
||||
customer.external_id = tryton_party.get("id")
|
||||
if tryton_party.get("addresses") and tryton_party.get("addresses")[0]:
|
||||
customer.address_external_id = tryton_party.get("addresses")[0]
|
||||
customer.save()
|
||||
@@ -1 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
33
tienda_ilusion/don_confiao/image_service.py
Normal file
33
tienda_ilusion/don_confiao/image_service.py
Normal file
@@ -0,0 +1,33 @@
|
||||
from django.conf import settings
|
||||
from PIL import Image
|
||||
|
||||
|
||||
def resize_catalogue_image(image_field):
|
||||
width = settings.CATALOGUE_IMAGE_WIDTH
|
||||
height = settings.CATALOGUE_IMAGE_HEIGHT
|
||||
strict = settings.CATALOGUE_STRICT_DIMENSION
|
||||
bg_color = settings.CATALOGUE_BACKGROUND_IMAGES_RGBA
|
||||
|
||||
img = Image.open(image_field.path)
|
||||
img = img.convert("RGBA")
|
||||
|
||||
if strict:
|
||||
img = resize_to_fit(img, width, height)
|
||||
canvas = Image.new("RGBA", (width, height), bg_color)
|
||||
x = (width - img.width) // 2
|
||||
y = (height - img.height) // 2
|
||||
canvas.paste(img, (x, y), img)
|
||||
img = canvas
|
||||
else:
|
||||
if img.width > width:
|
||||
new_height = int(img.height * width / img.width)
|
||||
img = img.resize((width, new_height), Image.LANCZOS)
|
||||
|
||||
img.save(image_field.path, format="PNG")
|
||||
|
||||
|
||||
def resize_to_fit(img, max_width, max_height):
|
||||
ratio = min(max_width / img.width, max_height / img.height)
|
||||
new_width = int(img.width * ratio)
|
||||
new_height = int(img.height * ratio)
|
||||
return img.resize((new_width, new_height), Image.LANCZOS)
|
||||
@@ -0,0 +1,18 @@
|
||||
# Generated by Django 5.0.6 on 2026-05-31 01:46
|
||||
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('don_confiao', '0046_product_active'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AddField(
|
||||
model_name='catalogsale',
|
||||
name='external_id',
|
||||
field=models.CharField(blank=True, max_length=100, null=True),
|
||||
),
|
||||
]
|
||||
@@ -0,0 +1,33 @@
|
||||
# Generated by Django 5.0.6 on 2026-06-05 14:02
|
||||
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('don_confiao', '0047_catalogsale_external_id'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AddField(
|
||||
model_name='catalogsale',
|
||||
name='customer_address',
|
||||
field=models.CharField(blank=True, max_length=255, null=True),
|
||||
),
|
||||
migrations.AddField(
|
||||
model_name='catalogsale',
|
||||
name='customer_name',
|
||||
field=models.CharField(blank=True, max_length=255, null=True),
|
||||
),
|
||||
migrations.AddField(
|
||||
model_name='catalogsale',
|
||||
name='customer_phone',
|
||||
field=models.CharField(blank=True, max_length=13, null=True),
|
||||
),
|
||||
migrations.AddField(
|
||||
model_name='catalogsale',
|
||||
name='pickup_method',
|
||||
field=models.CharField(blank=True, max_length=30, null=True),
|
||||
),
|
||||
]
|
||||
24
tienda_ilusion/don_confiao/migrations/0049_catalogueimage.py
Normal file
24
tienda_ilusion/don_confiao/migrations/0049_catalogueimage.py
Normal file
@@ -0,0 +1,24 @@
|
||||
# Generated by Django 5.0.6 on 2026-06-13 18:31
|
||||
|
||||
import django.db.models.deletion
|
||||
import don_confiao.models.catalogue_images
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('don_confiao', '0048_catalogsale_customer_address_and_more'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.CreateModel(
|
||||
name='CatalogueImage',
|
||||
fields=[
|
||||
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
|
||||
('image', models.ImageField(upload_to=don_confiao.models.catalogue_images._catalogue_image_upload_path)),
|
||||
('uploaded_at', models.DateTimeField(auto_now_add=True)),
|
||||
('product', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='catalogue_images', to='don_confiao.product')),
|
||||
],
|
||||
),
|
||||
]
|
||||
@@ -0,0 +1,24 @@
|
||||
# Generated by Django 5.0.6 on 2026-08-08 18:24
|
||||
|
||||
import don_confiao.models.sales
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('don_confiao', '0049_catalogueimage'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AddField(
|
||||
model_name='catalogsale',
|
||||
name='code',
|
||||
field=models.CharField(default=don_confiao.models.sales.generate_order_code, editable=False, max_length=32),
|
||||
),
|
||||
migrations.AddField(
|
||||
model_name='sale',
|
||||
name='code',
|
||||
field=models.CharField(default=don_confiao.models.sales.generate_order_code, editable=False, max_length=32),
|
||||
),
|
||||
]
|
||||
27
tienda_ilusion/don_confiao/migrations/0050_storesettings.py
Normal file
27
tienda_ilusion/don_confiao/migrations/0050_storesettings.py
Normal file
@@ -0,0 +1,27 @@
|
||||
# Generated by Django 5.0.6 on 2026-08-08 17:33
|
||||
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('don_confiao', '0049_catalogueimage'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.CreateModel(
|
||||
name='StoreSettings',
|
||||
fields=[
|
||||
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
|
||||
('address', models.TextField()),
|
||||
('latitude', models.FloatField(blank=True, null=True)),
|
||||
('longitude', models.FloatField(blank=True, null=True)),
|
||||
('updated_at', models.DateTimeField(auto_now=True)),
|
||||
],
|
||||
options={
|
||||
'verbose_name': 'Configuración de la tienda',
|
||||
'verbose_name_plural': 'Configuración de la tienda',
|
||||
},
|
||||
),
|
||||
]
|
||||
@@ -0,0 +1,18 @@
|
||||
# Generated by Django 5.0.6 on 2026-08-08 19:10
|
||||
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('don_confiao', '0050_storesettings'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AddField(
|
||||
model_name='storesettings',
|
||||
name='logo',
|
||||
field=models.ImageField(blank=True, null=True, upload_to='logos/'),
|
||||
),
|
||||
]
|
||||
@@ -0,0 +1,14 @@
|
||||
# Generated by Django 5.0.6 on 2026-08-10 03:51
|
||||
|
||||
from django.db import migrations
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('don_confiao', '0050_catalogsale_code_sale_code'),
|
||||
('don_confiao', '0051_storesettings_logo'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
]
|
||||
@@ -0,0 +1,3 @@
|
||||
from .store_settings import StoreSettings
|
||||
|
||||
__all__ = ["StoreSettings"]
|
||||
|
||||
20
tienda_ilusion/don_confiao/models/catalogue_images.py
Normal file
20
tienda_ilusion/don_confiao/models/catalogue_images.py
Normal file
@@ -0,0 +1,20 @@
|
||||
from django.db import models
|
||||
|
||||
from .products import Product
|
||||
|
||||
|
||||
def _catalogue_image_upload_path(instance, filename):
|
||||
return f"catalogue_images/{instance.product_id}/{filename}"
|
||||
|
||||
|
||||
class CatalogueImage(models.Model):
|
||||
product = models.ForeignKey(
|
||||
Product,
|
||||
on_delete=models.CASCADE,
|
||||
related_name="catalogue_images",
|
||||
)
|
||||
image = models.ImageField(upload_to=_catalogue_image_upload_path)
|
||||
uploaded_at = models.DateTimeField(auto_now_add=True)
|
||||
|
||||
def __str__(self):
|
||||
return f"CatalogueImage for {self.product.name} ({self.id})"
|
||||
@@ -4,6 +4,11 @@ from .products import Product
|
||||
from .payments import PaymentMethods, ReconciliationJar
|
||||
from django.core.exceptions import ValidationError
|
||||
from datetime import datetime
|
||||
import uuid
|
||||
|
||||
|
||||
def generate_order_code():
|
||||
return uuid.uuid4().hex
|
||||
|
||||
|
||||
class SaleAbstractModel(models.Model):
|
||||
@@ -11,6 +16,9 @@ class SaleAbstractModel(models.Model):
|
||||
date = models.DateTimeField("Date")
|
||||
phone = models.CharField(max_length=13, null=True, blank=True)
|
||||
description = models.CharField(max_length=255, null=True, blank=True)
|
||||
code = models.CharField(
|
||||
max_length=32, default=generate_order_code, editable=False
|
||||
)
|
||||
|
||||
class Meta:
|
||||
abstract = True
|
||||
@@ -67,7 +75,6 @@ class Sale(SaleAbstractModel):
|
||||
|
||||
|
||||
class SaleLine(SaleLineAbstractModel):
|
||||
|
||||
sale = models.ForeignKey(Sale, on_delete=models.CASCADE)
|
||||
|
||||
def __str__(self):
|
||||
@@ -75,6 +82,13 @@ class SaleLine(SaleLineAbstractModel):
|
||||
|
||||
|
||||
class CatalogSale(SaleAbstractModel):
|
||||
external_id = models.CharField(max_length=100, null=True, blank=True)
|
||||
customer_name = models.CharField(max_length=255, null=True, blank=True)
|
||||
customer_phone = models.CharField(max_length=13, null=True, blank=True)
|
||||
customer_address = models.CharField(
|
||||
max_length=255, null=True, blank=True
|
||||
)
|
||||
pickup_method = models.CharField(max_length=30, null=True, blank=True)
|
||||
|
||||
def __str__(self):
|
||||
return f"{self.date} {self.customer}"
|
||||
|
||||
21
tienda_ilusion/don_confiao/models/store_settings.py
Normal file
21
tienda_ilusion/don_confiao/models/store_settings.py
Normal file
@@ -0,0 +1,21 @@
|
||||
from django.db import models
|
||||
|
||||
|
||||
class StoreSettings(models.Model):
|
||||
address = models.TextField()
|
||||
latitude = models.FloatField(null=True, blank=True)
|
||||
longitude = models.FloatField(null=True, blank=True)
|
||||
logo = models.ImageField(upload_to="logos/", null=True, blank=True)
|
||||
updated_at = models.DateTimeField(auto_now=True)
|
||||
|
||||
class Meta:
|
||||
verbose_name = "Configuración de la tienda"
|
||||
verbose_name_plural = "Configuración de la tienda"
|
||||
|
||||
def __str__(self):
|
||||
return f"StoreSettings (id={self.id})"
|
||||
|
||||
@classmethod
|
||||
def get_singleton(cls):
|
||||
instance, _ = cls.objects.get_or_create(pk=1)
|
||||
return instance
|
||||
@@ -1,6 +1,26 @@
|
||||
from rest_framework.permissions import BasePermission
|
||||
|
||||
|
||||
def _get_user_type(user):
|
||||
if not user or not user.is_authenticated:
|
||||
return None
|
||||
profile = getattr(user, "profile", None)
|
||||
if profile:
|
||||
return profile.user_type
|
||||
return "administrator" if user.is_staff else "user"
|
||||
|
||||
|
||||
class IsAdministrator(BasePermission):
|
||||
def has_permission(self, request, view):
|
||||
return request.user and request.user.is_staff
|
||||
return _get_user_type(request.user) == "administrator"
|
||||
|
||||
|
||||
class IsNotPublico(BasePermission):
|
||||
def has_permission(self, request, view):
|
||||
user_type = _get_user_type(request.user)
|
||||
return user_type is not None and user_type != "publico"
|
||||
|
||||
|
||||
class IsPublico(BasePermission):
|
||||
def has_permission(self, request, view):
|
||||
return _get_user_type(request.user) == "publico"
|
||||
|
||||
45
tienda_ilusion/don_confiao/serializers/__init__.py
Normal file
45
tienda_ilusion/don_confiao/serializers/__init__.py
Normal file
@@ -0,0 +1,45 @@
|
||||
from .catalogue_images import CatalogueImageSerializer
|
||||
from .products import ProductSerializer, ListProductSerializer
|
||||
from .customers import CustomerSerializer, ListCustomerSerializer
|
||||
from .sales import (
|
||||
SaleSerializer,
|
||||
SaleLineSerializer,
|
||||
CatalogSaleSerializer,
|
||||
CatalogSaleLineSerializer,
|
||||
SummarySaleLineSerializer,
|
||||
SaleSummarySerializer,
|
||||
CatalogSummarySaleLineSerializer,
|
||||
CatalogSaleSummarySerializer,
|
||||
SaleForRenconciliationSerializer,
|
||||
)
|
||||
from .payments import (
|
||||
ReconciliationJarSerializer,
|
||||
PaymentMethodSerializer,
|
||||
)
|
||||
from .store_settings import StoreSettingsSerializer
|
||||
|
||||
__all__ = [
|
||||
# Catalogue Images
|
||||
"CatalogueImageSerializer",
|
||||
# Products
|
||||
"ProductSerializer",
|
||||
"ListProductSerializer",
|
||||
# Customers
|
||||
"CustomerSerializer",
|
||||
"ListCustomerSerializer",
|
||||
# Sales
|
||||
"SaleSerializer",
|
||||
"SaleLineSerializer",
|
||||
"CatalogSaleSerializer",
|
||||
"CatalogSaleLineSerializer",
|
||||
"SummarySaleLineSerializer",
|
||||
"SaleSummarySerializer",
|
||||
"CatalogSummarySaleLineSerializer",
|
||||
"CatalogSaleSummarySerializer",
|
||||
"SaleForRenconciliationSerializer",
|
||||
# Payments
|
||||
"ReconciliationJarSerializer",
|
||||
"PaymentMethodSerializer",
|
||||
# Store Settings
|
||||
"StoreSettingsSerializer",
|
||||
]
|
||||
20
tienda_ilusion/don_confiao/serializers/catalogue_images.py
Normal file
20
tienda_ilusion/don_confiao/serializers/catalogue_images.py
Normal file
@@ -0,0 +1,20 @@
|
||||
from django.conf import settings
|
||||
from rest_framework import serializers
|
||||
|
||||
from ..models.catalogue_images import CatalogueImage
|
||||
|
||||
|
||||
class CatalogueImageSerializer(serializers.ModelSerializer):
|
||||
class Meta:
|
||||
model = CatalogueImage
|
||||
fields = ["id", "product", "image", "uploaded_at"]
|
||||
read_only_fields = ["uploaded_at"]
|
||||
|
||||
def validate_image(self, value):
|
||||
max_size = settings.CATALOGUE_MAX_UPLOAD_SIZE
|
||||
if value.size > max_size:
|
||||
raise serializers.ValidationError(
|
||||
f"Image size exceeds the maximum allowed size of "
|
||||
f"{max_size // (1024 * 1024)}MB."
|
||||
)
|
||||
return value
|
||||
15
tienda_ilusion/don_confiao/serializers/customers.py
Normal file
15
tienda_ilusion/don_confiao/serializers/customers.py
Normal file
@@ -0,0 +1,15 @@
|
||||
from rest_framework import serializers
|
||||
|
||||
from ..models.customers import Customer
|
||||
|
||||
|
||||
class CustomerSerializer(serializers.ModelSerializer):
|
||||
class Meta:
|
||||
model = Customer
|
||||
fields = ["id", "name", "address", "email", "phone", "external_id"]
|
||||
|
||||
|
||||
class ListCustomerSerializer(serializers.ModelSerializer):
|
||||
class Meta:
|
||||
model = Customer
|
||||
fields = ["id", "name"]
|
||||
31
tienda_ilusion/don_confiao/serializers/payments.py
Normal file
31
tienda_ilusion/don_confiao/serializers/payments.py
Normal file
@@ -0,0 +1,31 @@
|
||||
from rest_framework import serializers
|
||||
|
||||
from ..models.payments import ReconciliationJar, PaymentMethods
|
||||
from .sales import SaleSerializer
|
||||
|
||||
|
||||
class ReconciliationJarSerializer(serializers.ModelSerializer):
|
||||
Sales = SaleSerializer(many=True, read_only=True)
|
||||
|
||||
class Meta:
|
||||
model = ReconciliationJar
|
||||
fields = [
|
||||
"id",
|
||||
"date_time",
|
||||
"reconcilier",
|
||||
"cash_taken",
|
||||
"cash_discrepancy",
|
||||
"total_cash_purchases",
|
||||
"Sales",
|
||||
]
|
||||
|
||||
|
||||
class PaymentMethodSerializer(serializers.Serializer):
|
||||
text = serializers.CharField()
|
||||
value = serializers.CharField()
|
||||
|
||||
def to_representation(self, instance):
|
||||
return {
|
||||
"text": instance[1],
|
||||
"value": instance[0],
|
||||
}
|
||||
46
tienda_ilusion/don_confiao/serializers/products.py
Normal file
46
tienda_ilusion/don_confiao/serializers/products.py
Normal file
@@ -0,0 +1,46 @@
|
||||
from rest_framework import serializers
|
||||
|
||||
from ..models.products import Product, ProductCategory
|
||||
|
||||
|
||||
class ProductSerializer(serializers.ModelSerializer):
|
||||
catalogue_images = serializers.SerializerMethodField()
|
||||
|
||||
class Meta:
|
||||
model = Product
|
||||
fields = [
|
||||
"id",
|
||||
"name",
|
||||
"active",
|
||||
"price",
|
||||
"measuring_unit",
|
||||
"categories",
|
||||
"external_id",
|
||||
"catalogue_images",
|
||||
]
|
||||
|
||||
def get_catalogue_images(self, obj):
|
||||
request = self.context.get("request")
|
||||
if not request:
|
||||
return [img.image.url for img in obj.catalogue_images.all()]
|
||||
return [
|
||||
request.build_absolute_uri(img.image.url)
|
||||
for img in obj.catalogue_images.all()
|
||||
]
|
||||
|
||||
|
||||
class ListProductSerializer(serializers.ModelSerializer):
|
||||
catalogue_images = serializers.SerializerMethodField()
|
||||
|
||||
class Meta:
|
||||
model = Product
|
||||
fields = ["id", "name", "catalogue_images"]
|
||||
|
||||
def get_catalogue_images(self, obj):
|
||||
request = self.context.get("request")
|
||||
if not request:
|
||||
return [img.image.url for img in obj.catalogue_images.all()]
|
||||
return [
|
||||
request.build_absolute_uri(img.image.url)
|
||||
for img in obj.catalogue_images.all()
|
||||
]
|
||||
@@ -1,16 +1,26 @@
|
||||
from rest_framework import serializers
|
||||
from django.urls import reverse
|
||||
|
||||
from .models.sales import Sale, SaleLine
|
||||
from .models.customers import Customer
|
||||
from .models.sales import (
|
||||
from ..models.sales import (
|
||||
Sale,
|
||||
SaleLine,
|
||||
CatalogSale,
|
||||
CatalogSaleLine,
|
||||
Payment,
|
||||
)
|
||||
from .models.products import Product, ProductCategory
|
||||
from .models.payments import ReconciliationJar
|
||||
from .products import ListProductSerializer
|
||||
from .customers import ListCustomerSerializer
|
||||
|
||||
|
||||
class PublicSummaryLinkMixin:
|
||||
def get_link(self, obj):
|
||||
path = reverse(
|
||||
"don_confiao:public_purchase_summary", args=[obj.code]
|
||||
)
|
||||
request = self.context.get("request")
|
||||
if request:
|
||||
return request.build_absolute_uri(path)
|
||||
return path
|
||||
|
||||
|
||||
class SaleLineSerializer(serializers.ModelSerializer):
|
||||
@@ -26,6 +36,7 @@ class SaleSerializer(serializers.ModelSerializer):
|
||||
model = Sale
|
||||
fields = [
|
||||
"id",
|
||||
"code",
|
||||
"customer",
|
||||
"date",
|
||||
"saleline_set",
|
||||
@@ -58,10 +69,16 @@ class CatalogSaleSerializer(serializers.ModelSerializer):
|
||||
model = CatalogSale
|
||||
fields = [
|
||||
"id",
|
||||
"code",
|
||||
"customer",
|
||||
"date",
|
||||
"catalogsaleline_set",
|
||||
"total",
|
||||
"external_id",
|
||||
"customer_name",
|
||||
"customer_phone",
|
||||
"customer_address",
|
||||
"pickup_method",
|
||||
]
|
||||
|
||||
def create(self, validated_data):
|
||||
@@ -76,51 +93,44 @@ class CatalogSaleSerializer(serializers.ModelSerializer):
|
||||
return catalog_sale
|
||||
|
||||
|
||||
class ProductSerializer(serializers.ModelSerializer):
|
||||
class Meta:
|
||||
model = Product
|
||||
fields = [
|
||||
"id",
|
||||
"name",
|
||||
"active",
|
||||
"price",
|
||||
"measuring_unit",
|
||||
"categories",
|
||||
"external_id",
|
||||
]
|
||||
|
||||
|
||||
class CustomerSerializer(serializers.ModelSerializer):
|
||||
class Meta:
|
||||
model = Customer
|
||||
fields = ["id", "name", "address", "email", "phone", "external_id"]
|
||||
|
||||
|
||||
class ReconciliationJarSerializer(serializers.ModelSerializer):
|
||||
Sales = SaleSerializer(many=True, read_only=True)
|
||||
class SummarySaleLineSerializer(serializers.ModelSerializer):
|
||||
product = ListProductSerializer()
|
||||
|
||||
class Meta:
|
||||
model = ReconciliationJar
|
||||
fields = [
|
||||
"id",
|
||||
"date_time",
|
||||
"reconcilier",
|
||||
"cash_taken",
|
||||
"cash_discrepancy",
|
||||
"total_cash_purchases",
|
||||
"Sales",
|
||||
]
|
||||
model = SaleLine
|
||||
fields = ["product", "quantity", "unit_price", "description"]
|
||||
|
||||
|
||||
class PaymentMethodSerializer(serializers.Serializer):
|
||||
text = serializers.CharField()
|
||||
value = serializers.CharField()
|
||||
class SaleSummarySerializer(PublicSummaryLinkMixin, serializers.ModelSerializer):
|
||||
customer = ListCustomerSerializer()
|
||||
lines = SummarySaleLineSerializer(many=True, source="saleline_set")
|
||||
link = serializers.SerializerMethodField()
|
||||
|
||||
def to_representation(self, instance):
|
||||
return {
|
||||
"text": instance[1],
|
||||
"value": instance[0],
|
||||
}
|
||||
class Meta:
|
||||
model = Sale
|
||||
fields = ["id", "code", "date", "customer", "payment_method", "lines", "link"]
|
||||
|
||||
|
||||
class CatalogSummarySaleLineSerializer(serializers.ModelSerializer):
|
||||
product = ListProductSerializer()
|
||||
|
||||
class Meta:
|
||||
model = CatalogSaleLine
|
||||
fields = ["product", "quantity", "unit_price", "description"]
|
||||
|
||||
|
||||
class CatalogSaleSummarySerializer(
|
||||
PublicSummaryLinkMixin, serializers.ModelSerializer
|
||||
):
|
||||
customer = ListCustomerSerializer()
|
||||
lines = CatalogSummarySaleLineSerializer(
|
||||
many=True, source="catalogsaleline_set"
|
||||
)
|
||||
link = serializers.SerializerMethodField()
|
||||
|
||||
class Meta:
|
||||
model = CatalogSale
|
||||
fields = ["id", "code", "date", "customer", "lines", "link"]
|
||||
|
||||
|
||||
class SaleForRenconciliationSerializer(serializers.Serializer):
|
||||
@@ -138,32 +148,3 @@ class SaleForRenconciliationSerializer(serializers.Serializer):
|
||||
|
||||
def get_total(self, sale):
|
||||
return sale.get_total()
|
||||
|
||||
|
||||
class ListCustomerSerializer(serializers.ModelSerializer):
|
||||
class Meta:
|
||||
model = Customer
|
||||
fields = ["id", "name"]
|
||||
|
||||
|
||||
class ListProductSerializer(serializers.ModelSerializer):
|
||||
class Meta:
|
||||
model = Product
|
||||
fields = ["id", "name"]
|
||||
|
||||
|
||||
class SummarySaleLineSerializer(serializers.ModelSerializer):
|
||||
product = ListProductSerializer()
|
||||
|
||||
class Meta:
|
||||
model = SaleLine
|
||||
fields = ["product", "quantity", "unit_price", "description"]
|
||||
|
||||
|
||||
class SaleSummarySerializer(serializers.ModelSerializer):
|
||||
customer = ListCustomerSerializer()
|
||||
lines = SummarySaleLineSerializer(many=True, source="saleline_set")
|
||||
|
||||
class Meta:
|
||||
model = Sale
|
||||
fields = ["id", "date", "customer", "payment_method", "lines"]
|
||||
22
tienda_ilusion/don_confiao/serializers/store_settings.py
Normal file
22
tienda_ilusion/don_confiao/serializers/store_settings.py
Normal file
@@ -0,0 +1,22 @@
|
||||
from django.conf import settings
|
||||
from rest_framework import serializers
|
||||
|
||||
from ..models.store_settings import StoreSettings
|
||||
|
||||
|
||||
class StoreSettingsSerializer(serializers.ModelSerializer):
|
||||
class Meta:
|
||||
model = StoreSettings
|
||||
fields = ["id", "address", "latitude", "longitude", "logo", "updated_at"]
|
||||
read_only_fields = ["id", "updated_at"]
|
||||
|
||||
def validate_logo(self, value):
|
||||
if value is None:
|
||||
return value
|
||||
max_size = settings.LOGO_MAX_UPLOAD_SIZE
|
||||
if value.size > max_size:
|
||||
raise serializers.ValidationError(
|
||||
f"Logo size exceeds the maximum allowed size of "
|
||||
f"{max_size // (1024 * 1024)}MB."
|
||||
)
|
||||
return value
|
||||
13
tienda_ilusion/don_confiao/services/__init__.py
Normal file
13
tienda_ilusion/don_confiao/services/__init__.py
Normal file
@@ -0,0 +1,13 @@
|
||||
from .tryton import (
|
||||
get_tryton_client,
|
||||
ProductTrytonService,
|
||||
CustomerTrytonService,
|
||||
SaleTrytonService,
|
||||
)
|
||||
|
||||
__all__ = [
|
||||
"get_tryton_client",
|
||||
"ProductTrytonService",
|
||||
"CustomerTrytonService",
|
||||
"SaleTrytonService",
|
||||
]
|
||||
13
tienda_ilusion/don_confiao/services/tryton/__init__.py
Normal file
13
tienda_ilusion/don_confiao/services/tryton/__init__.py
Normal file
@@ -0,0 +1,13 @@
|
||||
from .client import get_tryton_client, TrytonSale, TrytonLineSale
|
||||
from .products import ProductTrytonService
|
||||
from .customers import CustomerTrytonService
|
||||
from .sales import SaleTrytonService
|
||||
|
||||
__all__ = [
|
||||
"get_tryton_client",
|
||||
"TrytonSale",
|
||||
"TrytonLineSale",
|
||||
"ProductTrytonService",
|
||||
"CustomerTrytonService",
|
||||
"SaleTrytonService",
|
||||
]
|
||||
160
tienda_ilusion/don_confiao/services/tryton/client.py
Normal file
160
tienda_ilusion/don_confiao/services/tryton/client.py
Normal file
@@ -0,0 +1,160 @@
|
||||
import os
|
||||
from sabatron_tryton_rpc_client.client import Client
|
||||
|
||||
TRYTON_HOST = os.environ.get("TRYTON_HOST", "localhost")
|
||||
TRYTON_DATABASE = os.environ.get("TRYTON_DATABASE", "tryton")
|
||||
TRYTON_USERNAME = os.environ.get("TRYTON_USERNAME", "admin")
|
||||
TRYTON_PASSWORD = os.environ.get("TRYTON_PASSWORD", "admin")
|
||||
TRYTON_COP_CURRENCY = 31
|
||||
TRYTON_COMPANY_ID = 1
|
||||
TRYTON_SHOPS = [1]
|
||||
|
||||
|
||||
def get_tryton_client():
|
||||
"""Factory para crear cliente Tryton conectado"""
|
||||
client = Client(
|
||||
hostname=TRYTON_HOST,
|
||||
database=TRYTON_DATABASE,
|
||||
username=TRYTON_USERNAME,
|
||||
password=TRYTON_PASSWORD,
|
||||
)
|
||||
client.connect()
|
||||
return client
|
||||
|
||||
|
||||
class TrytonSale:
|
||||
"""Representa una venta para exportación a Tryton"""
|
||||
|
||||
def __init__(self, sale, lines):
|
||||
self.sale = sale
|
||||
self.lines = lines
|
||||
|
||||
def _format_date(self, _date):
|
||||
return {
|
||||
"__class__": "date",
|
||||
"year": _date.year,
|
||||
"month": _date.month,
|
||||
"day": _date.day,
|
||||
}
|
||||
|
||||
def to_tryton(self):
|
||||
return {
|
||||
"company": TRYTON_COMPANY_ID,
|
||||
"shipment_address": self.sale.customer.address_external_id,
|
||||
"invoice_address": self.sale.customer.address_external_id,
|
||||
"currency": TRYTON_COP_CURRENCY,
|
||||
"comment": self.build_tryton_comment(),
|
||||
"description": "Metodo pago: "
|
||||
+ str(self.sale.payment_method or ""),
|
||||
"party": self.sale.customer.external_id,
|
||||
"reference": "don_confiao " + str(self.sale.id),
|
||||
"sale_date": self._format_date(self.sale.date),
|
||||
"lines": [
|
||||
[
|
||||
"create",
|
||||
[
|
||||
TrytonLineSale(line).to_tryton()
|
||||
for line in self.lines
|
||||
],
|
||||
]
|
||||
],
|
||||
"self_pick_up": True,
|
||||
}
|
||||
|
||||
def build_tryton_comment(self):
|
||||
"""Construye el comentario para la venta en Tryton"""
|
||||
return self.sale.description or ""
|
||||
|
||||
|
||||
class TrytonLineSale:
|
||||
"""Representa una línea de venta para exportación a Tryton"""
|
||||
|
||||
def __init__(self, sale_line):
|
||||
self.sale_line = sale_line
|
||||
|
||||
def _format_decimal(self, number):
|
||||
return {"__class__": "Decimal", "decimal": str(number)}
|
||||
|
||||
def to_tryton(self):
|
||||
return {
|
||||
"product": self.sale_line.product.external_id,
|
||||
"quantity": self._format_decimal(self.sale_line.quantity),
|
||||
"type": "line",
|
||||
"unit": self.sale_line.product.unit_external_id,
|
||||
"unit_price": self._format_decimal(self.sale_line.unit_price),
|
||||
}
|
||||
|
||||
|
||||
class TrytonCatalogSale:
|
||||
"""Representa una catalog sale para exportación a Tryton"""
|
||||
|
||||
def __init__(self, catalog_sale, lines):
|
||||
self.catalog_sale = catalog_sale
|
||||
self.lines = lines
|
||||
|
||||
def _format_date(self, _date):
|
||||
return {
|
||||
"__class__": "date",
|
||||
"year": _date.year,
|
||||
"month": _date.month,
|
||||
"day": _date.day,
|
||||
}
|
||||
|
||||
def to_tryton(self):
|
||||
return {
|
||||
"company": TRYTON_COMPANY_ID,
|
||||
"shipment_address": self.catalog_sale.customer.address_external_id,
|
||||
"invoice_address": self.catalog_sale.customer.address_external_id,
|
||||
"currency": TRYTON_COP_CURRENCY,
|
||||
"comment": self.build_tryton_comment(),
|
||||
"description": "Venta de catálogo",
|
||||
"party": self.catalog_sale.customer.external_id,
|
||||
"reference": "don_confiao_catalog "
|
||||
+ str(self.catalog_sale.id),
|
||||
"sale_date": self._format_date(self.catalog_sale.date),
|
||||
"lines": [
|
||||
[
|
||||
"create",
|
||||
[
|
||||
TrytonCatalogSaleLine(line).to_tryton()
|
||||
for line in self.lines
|
||||
],
|
||||
]
|
||||
],
|
||||
"self_pick_up": True,
|
||||
}
|
||||
|
||||
def build_tryton_comment(self):
|
||||
"""Construye el comentario para la venta en Tryton"""
|
||||
|
||||
comment = f"Cliente: {self.catalog_sale.customer_name or ''}\n"
|
||||
comment += f"Teléfono: {self.catalog_sale.customer_phone or ''}\n"
|
||||
comment += (
|
||||
f"Dirección: {self.catalog_sale.customer_address or ''}\n"
|
||||
)
|
||||
comment += f"Método de recogida: {self.catalog_sale.pickup_method or ''}\n"
|
||||
|
||||
return comment
|
||||
|
||||
|
||||
class TrytonCatalogSaleLine:
|
||||
"""Representa una línea de catalog sale para exportación a Tryton"""
|
||||
|
||||
def __init__(self, catalog_sale_line):
|
||||
self.catalog_sale_line = catalog_sale_line
|
||||
|
||||
def _format_decimal(self, number):
|
||||
return {"__class__": "Decimal", "decimal": str(number)}
|
||||
|
||||
def to_tryton(self):
|
||||
return {
|
||||
"product": self.catalog_sale_line.product.external_id,
|
||||
"quantity": self._format_decimal(
|
||||
self.catalog_sale_line.quantity
|
||||
),
|
||||
"type": "line",
|
||||
"unit": self.catalog_sale_line.product.unit_external_id,
|
||||
"unit_price": self._format_decimal(
|
||||
self.catalog_sale_line.unit_price
|
||||
),
|
||||
}
|
||||
81
tienda_ilusion/don_confiao/services/tryton/customers.py
Normal file
81
tienda_ilusion/don_confiao/services/tryton/customers.py
Normal file
@@ -0,0 +1,81 @@
|
||||
from ...models.customers import Customer
|
||||
|
||||
|
||||
class CustomerTrytonService:
|
||||
"""Servicio para sincronización de clientes con Tryton"""
|
||||
|
||||
def __init__(self, tryton_client):
|
||||
self.client = tryton_client
|
||||
|
||||
def import_from_tryton(self):
|
||||
"""Importa clientes desde Tryton"""
|
||||
method = "model.party.party.search"
|
||||
context = {"company": 1}
|
||||
params = [[], 0, 1000, [["name", "ASC"], ["id", None]], context]
|
||||
party_ids = self.client.call(method, params)
|
||||
tryton_parties = self._get_party_details(party_ids, context)
|
||||
|
||||
checked_tryton_parties = party_ids
|
||||
failed_parties = []
|
||||
updated_customers = []
|
||||
created_customers = []
|
||||
untouched_customers = []
|
||||
|
||||
for tryton_party in tryton_parties:
|
||||
try:
|
||||
customer = Customer.objects.get(external_id=tryton_party.get("id"))
|
||||
except Customer.DoesNotExist:
|
||||
customer = self._create_customer(tryton_party)
|
||||
created_customers.append(customer.id)
|
||||
continue
|
||||
|
||||
if self._need_update(customer, tryton_party):
|
||||
self._update_customer(customer, tryton_party)
|
||||
updated_customers.append(customer.id)
|
||||
else:
|
||||
untouched_customers.append(customer.id)
|
||||
|
||||
return {
|
||||
"checked_tryton_parties": checked_tryton_parties,
|
||||
"failed_parties": failed_parties,
|
||||
"updated_customers": updated_customers,
|
||||
"created_customers": created_customers,
|
||||
"untouched_customers": untouched_customers,
|
||||
}
|
||||
|
||||
def _get_party_details(self, party_ids, context):
|
||||
"""Obtiene detalles de clientes desde Tryton"""
|
||||
tryton_fields = ["id", "name", "addresses"]
|
||||
method = "model.party.party.read"
|
||||
params = (party_ids, tryton_fields, context)
|
||||
response = self.client.call(method, params)
|
||||
return response
|
||||
|
||||
def _need_update(self, customer, tryton_party):
|
||||
"""Verifica si el cliente necesita actualización"""
|
||||
if not customer.name == tryton_party.get("name"):
|
||||
return True
|
||||
if tryton_party.get("addresses") and tryton_party.get("addresses")[0]:
|
||||
if not customer.address_external_id == str(
|
||||
tryton_party.get("addresses")[0]
|
||||
):
|
||||
return True
|
||||
return False
|
||||
|
||||
def _create_customer(self, tryton_party):
|
||||
"""Crea un nuevo cliente desde datos de Tryton"""
|
||||
customer = Customer()
|
||||
customer.name = tryton_party.get("name")
|
||||
customer.external_id = tryton_party.get("id")
|
||||
if tryton_party.get("addresses") and tryton_party.get("addresses")[0]:
|
||||
customer.address_external_id = tryton_party.get("addresses")[0]
|
||||
customer.save()
|
||||
return customer
|
||||
|
||||
def _update_customer(self, customer, tryton_party):
|
||||
"""Actualiza un cliente existente con datos de Tryton"""
|
||||
customer.name = tryton_party.get("name")
|
||||
customer.external_id = tryton_party.get("id")
|
||||
if tryton_party.get("addresses") and tryton_party.get("addresses")[0]:
|
||||
customer.address_external_id = tryton_party.get("addresses")[0]
|
||||
customer.save()
|
||||
104
tienda_ilusion/don_confiao/services/tryton/products.py
Normal file
104
tienda_ilusion/don_confiao/services/tryton/products.py
Normal file
@@ -0,0 +1,104 @@
|
||||
from ...models.products import Product
|
||||
|
||||
|
||||
class ProductTrytonService:
|
||||
"""Servicio para sincronización de productos con Tryton"""
|
||||
|
||||
def __init__(self, tryton_client):
|
||||
self.client = tryton_client
|
||||
|
||||
def import_from_tryton(self):
|
||||
"""Importa productos desde Tryton"""
|
||||
method = "model.product.product.search"
|
||||
context = {"company": 1}
|
||||
params = [
|
||||
[["salable", "=", True]],
|
||||
0,
|
||||
1000,
|
||||
[["rec_name", "ASC"], ["id", None]],
|
||||
context,
|
||||
]
|
||||
product_ids = self.client.call(method, params)
|
||||
tryton_products = self._get_product_details(product_ids, context)
|
||||
|
||||
checked_tryton_products = product_ids
|
||||
failed_products = []
|
||||
updated_products = []
|
||||
created_products = []
|
||||
untouched_products = []
|
||||
|
||||
for tryton_product in tryton_products:
|
||||
try:
|
||||
product = Product.objects.get(external_id=tryton_product.get("id"))
|
||||
except Product.DoesNotExist:
|
||||
try:
|
||||
product = self._create_product(tryton_product)
|
||||
created_products.append(product.id)
|
||||
continue
|
||||
except Exception as e:
|
||||
print(
|
||||
f"Error al importar productos: {e}El producto: {tryton_product}"
|
||||
)
|
||||
failed_products.append(tryton_product.get("id"))
|
||||
continue
|
||||
|
||||
if self._need_update(product, tryton_product):
|
||||
self._update_product(product, tryton_product)
|
||||
updated_products.append(product.id)
|
||||
else:
|
||||
untouched_products.append(product.id)
|
||||
|
||||
return {
|
||||
"checked_tryton_products": checked_tryton_products,
|
||||
"failed_products": failed_products,
|
||||
"updated_products": updated_products,
|
||||
"created_products": created_products,
|
||||
"untouched_products": untouched_products,
|
||||
}
|
||||
|
||||
def _get_product_details(self, product_ids, context):
|
||||
"""Obtiene detalles de productos desde Tryton"""
|
||||
tryton_fields = [
|
||||
"id",
|
||||
"name",
|
||||
"default_uom.id",
|
||||
"default_uom.rec_name",
|
||||
"list_price",
|
||||
]
|
||||
method = "model.product.product.read"
|
||||
params = (product_ids, tryton_fields, context)
|
||||
response = self.client.call(method, params)
|
||||
return response
|
||||
|
||||
def _need_update(self, product, tryton_product):
|
||||
"""Verifica si el producto necesita actualización"""
|
||||
if not product.name == tryton_product.get("name"):
|
||||
return True
|
||||
if not product.price == tryton_product.get("list_price"):
|
||||
return True
|
||||
unit = tryton_product.get("default_uom.")
|
||||
if not product.measuring_unit == unit.get("rec_name"):
|
||||
return True
|
||||
return False
|
||||
|
||||
def _create_product(self, tryton_product):
|
||||
"""Crea un nuevo producto desde datos de Tryton"""
|
||||
product = Product()
|
||||
product.name = tryton_product.get("name")
|
||||
product.price = tryton_product.get("list_price")
|
||||
product.external_id = tryton_product.get("id")
|
||||
unit = tryton_product.get("default_uom.")
|
||||
product.measuring_unit = unit.get("rec_name")
|
||||
product.unit_external_id = unit.get("id")
|
||||
product.save()
|
||||
return product
|
||||
|
||||
def _update_product(self, product, tryton_product):
|
||||
"""Actualiza un producto existente con datos de Tryton"""
|
||||
product.name = tryton_product.get("name")
|
||||
product.price = tryton_product.get("list_price")
|
||||
product.external_id = tryton_product.get("id")
|
||||
unit = tryton_product.get("default_uom.")
|
||||
product.measuring_unit = unit.get("rec_name")
|
||||
product.unit_external_id = unit.get("id")
|
||||
product.save()
|
||||
77
tienda_ilusion/don_confiao/services/tryton/sales.py
Normal file
77
tienda_ilusion/don_confiao/services/tryton/sales.py
Normal file
@@ -0,0 +1,77 @@
|
||||
from ...models.sales import Sale, SaleLine, CatalogSale, CatalogSaleLine
|
||||
from .client import TrytonSale, TrytonCatalogSale, TRYTON_COMPANY_ID, TRYTON_SHOPS
|
||||
|
||||
|
||||
class SaleTrytonService:
|
||||
"""Servicio para sincronización de ventas con Tryton"""
|
||||
|
||||
def __init__(self, tryton_client):
|
||||
self.client = tryton_client
|
||||
|
||||
def send_to_tryton(self):
|
||||
"""Envía ventas sin external_id a Tryton"""
|
||||
method = "model.sale.sale.create"
|
||||
tryton_context = {
|
||||
"company": TRYTON_COMPANY_ID,
|
||||
"shops": TRYTON_SHOPS,
|
||||
}
|
||||
|
||||
successful = []
|
||||
failed = []
|
||||
|
||||
sales = Sale.objects.filter(external_id=None)
|
||||
for sale in sales:
|
||||
try:
|
||||
lines = SaleLine.objects.filter(sale=sale.id)
|
||||
tryton_params = self._to_tryton_params(sale, lines, tryton_context)
|
||||
external_ids = self.client.call(method, tryton_params)
|
||||
sale.external_id = external_ids[0]
|
||||
sale.save()
|
||||
successful.append(sale.id)
|
||||
except Exception as e:
|
||||
print(f"Error al enviar la venta: {e}venta_id: {sale.id}")
|
||||
failed.append(sale.id)
|
||||
continue
|
||||
|
||||
return {"successful": successful, "failed": failed}
|
||||
|
||||
def _to_tryton_params(self, sale, lines, tryton_context):
|
||||
"""Convierte venta a parámetros para Tryton"""
|
||||
sale_tryton = TrytonSale(sale, lines)
|
||||
return [[sale_tryton.to_tryton()], tryton_context]
|
||||
|
||||
def send_catalog_sales_to_tryton(self):
|
||||
"""Envía catalog sales sin external_id a Tryton"""
|
||||
method = "model.sale.sale.create"
|
||||
tryton_context = {
|
||||
"company": TRYTON_COMPANY_ID,
|
||||
"shops": TRYTON_SHOPS,
|
||||
}
|
||||
|
||||
successful = []
|
||||
failed = []
|
||||
|
||||
catalog_sales = CatalogSale.objects.filter(external_id=None)
|
||||
for catalog_sale in catalog_sales:
|
||||
try:
|
||||
lines = CatalogSaleLine.objects.filter(catalog_sale=catalog_sale.id)
|
||||
tryton_params = self._catalog_sale_to_tryton_params(
|
||||
catalog_sale, lines, tryton_context
|
||||
)
|
||||
external_ids = self.client.call(method, tryton_params)
|
||||
catalog_sale.external_id = external_ids[0]
|
||||
catalog_sale.save()
|
||||
successful.append(catalog_sale.id)
|
||||
except Exception as e:
|
||||
print(
|
||||
f"Error al enviar catalog sale: {e}, catalog_sale_id: {catalog_sale.id}"
|
||||
)
|
||||
failed.append(catalog_sale.id)
|
||||
continue
|
||||
|
||||
return {"successful": successful, "failed": failed}
|
||||
|
||||
def _catalog_sale_to_tryton_params(self, catalog_sale, lines, tryton_context):
|
||||
"""Convierte catalog sale a parámetros para Tryton"""
|
||||
sale_tryton = TrytonCatalogSale(catalog_sale, lines)
|
||||
return [[sale_tryton.to_tryton()], tryton_context]
|
||||
@@ -86,6 +86,67 @@ class TestAPI(APITestCase, LoginMixin):
|
||||
self.assertIn("csv", json_response)
|
||||
self.assertGreater(len(json_response["csv"]), 0)
|
||||
|
||||
def test_catalog_sale_summary(self):
|
||||
# Create a catalog sale
|
||||
response = self._create_catalog_sale()
|
||||
content = json.loads(response.content.decode("utf-8"))
|
||||
catalog_sale_id = content["id"]
|
||||
|
||||
# Get the summary
|
||||
url = f"/don_confiao/resumen_compra_catalogo_json/{catalog_sale_id}"
|
||||
response = self.client.get(url)
|
||||
|
||||
# Verify response
|
||||
self.assertEqual(response.status_code, status.HTTP_200_OK)
|
||||
json_response = json.loads(response.content.decode("utf-8"))
|
||||
|
||||
# Verify structure
|
||||
self.assertIn("id", json_response)
|
||||
self.assertIn("date", json_response)
|
||||
self.assertIn("customer", json_response)
|
||||
self.assertIn("lines", json_response)
|
||||
|
||||
# Verify customer details
|
||||
self.assertEqual(json_response["customer"]["id"], self.customer.id)
|
||||
self.assertEqual(json_response["customer"]["name"], self.customer.name)
|
||||
|
||||
# Verify lines
|
||||
self.assertEqual(len(json_response["lines"]), 2)
|
||||
|
||||
# Verify first line
|
||||
line1 = json_response["lines"][0]
|
||||
self.assertIn("product", line1)
|
||||
self.assertIn("quantity", line1)
|
||||
self.assertIn("unit_price", line1)
|
||||
self.assertEqual(line1["product"]["id"], self.product.id)
|
||||
self.assertEqual(line1["product"]["name"], self.product.name)
|
||||
self.assertEqual(line1["quantity"], "2.00")
|
||||
self.assertEqual(line1["unit_price"], "3000.00")
|
||||
|
||||
# Verify second line
|
||||
line2 = json_response["lines"][1]
|
||||
self.assertEqual(line2["product"]["id"], self.product.id)
|
||||
self.assertEqual(line2["quantity"], "3.00")
|
||||
self.assertEqual(line2["unit_price"], "5000.00")
|
||||
|
||||
def test_catalog_sale_has_external_id_field(self):
|
||||
"""Verifica que CatalogSale tiene el campo external_id"""
|
||||
response = self._create_catalog_sale()
|
||||
content = json.loads(response.content.decode("utf-8"))
|
||||
catalog_sale_id = content["id"]
|
||||
|
||||
catalog_sale = CatalogSale.objects.get(pk=catalog_sale_id)
|
||||
# Debe tener el campo external_id
|
||||
self.assertIsNone(catalog_sale.external_id)
|
||||
|
||||
# Se puede asignar un valor
|
||||
catalog_sale.external_id = "123"
|
||||
catalog_sale.save()
|
||||
|
||||
# Verificar que se guardó
|
||||
catalog_sale.refresh_from_db()
|
||||
self.assertEqual(catalog_sale.external_id, "123")
|
||||
|
||||
def test_csv_structure_in_sales_for_tryton(self):
|
||||
url = "/don_confiao/api/sales/for_tryton"
|
||||
self._create_sale()
|
||||
|
||||
408
tienda_ilusion/don_confiao/tests/test_catalogue_images.py
Normal file
408
tienda_ilusion/don_confiao/tests/test_catalogue_images.py
Normal file
@@ -0,0 +1,408 @@
|
||||
import io
|
||||
|
||||
from django.conf import settings
|
||||
from django.contrib.auth.models import User
|
||||
from django.core.files.uploadedfile import SimpleUploadedFile
|
||||
from django.test import override_settings
|
||||
from PIL import Image
|
||||
from rest_framework import status
|
||||
from rest_framework.test import APIClient, APITestCase
|
||||
from rest_framework_simplejwt.tokens import RefreshToken
|
||||
|
||||
from ..models.catalogue_images import CatalogueImage
|
||||
from ..models.products import Product
|
||||
from .Mixins import LoginMixin
|
||||
|
||||
|
||||
def _create_test_image(width=600, height=400, name="test.png"):
|
||||
"""Create a SimpleUploadedFile from an in-memory image using PIL."""
|
||||
img = Image.new("RGBA", (width, height), (255, 0, 0, 255))
|
||||
output = io.BytesIO()
|
||||
img.save(output, format="PNG")
|
||||
return SimpleUploadedFile(
|
||||
name=name,
|
||||
content=output.getvalue(),
|
||||
content_type="image/png",
|
||||
)
|
||||
|
||||
|
||||
class TestCatalogueImageModel(APITestCase, LoginMixin):
|
||||
def setUp(self):
|
||||
self.login()
|
||||
self.product = Product.objects.create(
|
||||
name="Test Product", price=100.00
|
||||
)
|
||||
|
||||
def test_create_catalogue_image(self):
|
||||
image_file = _create_test_image()
|
||||
catalogue_image = CatalogueImage.objects.create(
|
||||
product=self.product, image=image_file
|
||||
)
|
||||
self.assertIsInstance(catalogue_image, CatalogueImage)
|
||||
self.assertEqual(catalogue_image.product, self.product)
|
||||
self.assertIsNotNone(catalogue_image.image)
|
||||
self.assertIsNotNone(catalogue_image.uploaded_at)
|
||||
|
||||
def test_catalogue_image_product_relation(self):
|
||||
image_file = _create_test_image()
|
||||
ci = CatalogueImage.objects.create(
|
||||
product=self.product, image=image_file
|
||||
)
|
||||
self.assertIn(ci, self.product.catalogue_images.all())
|
||||
|
||||
def test_catalogue_image_str(self):
|
||||
image_file = _create_test_image()
|
||||
ci = CatalogueImage.objects.create(
|
||||
product=self.product, image=image_file
|
||||
)
|
||||
expected = f"CatalogueImage for {self.product.name} ({ci.id})"
|
||||
self.assertEqual(str(ci), expected)
|
||||
|
||||
def test_cascade_delete_with_product(self):
|
||||
image_file = _create_test_image()
|
||||
CatalogueImage.objects.create(
|
||||
product=self.product, image=image_file
|
||||
)
|
||||
self.assertEqual(CatalogueImage.objects.count(), 1)
|
||||
self.product.delete()
|
||||
self.assertEqual(CatalogueImage.objects.count(), 0)
|
||||
|
||||
|
||||
class TestCatalogueImageAPIPermissions(APITestCase, LoginMixin):
|
||||
def setUp(self):
|
||||
self.product = Product.objects.create(
|
||||
name="Perm Test Product", price=100.00
|
||||
)
|
||||
|
||||
def test_create_catalogue_image_unauthenticated(self):
|
||||
url = "/don_confiao/api/catalogue_images/"
|
||||
image_file = _create_test_image()
|
||||
data = {"product": self.product.id, "image": image_file}
|
||||
response = self.client.post(url, data, format="multipart")
|
||||
self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)
|
||||
|
||||
def test_create_catalogue_image_non_admin(self):
|
||||
self.user = User.objects.create_user(
|
||||
username="regularuser",
|
||||
email="regular@example.com",
|
||||
password="regularpass",
|
||||
)
|
||||
refresh = RefreshToken.for_user(self.user)
|
||||
self.client = APIClient()
|
||||
self.client.credentials(
|
||||
HTTP_AUTHORIZATION=f"Bearer {str(refresh.access_token)}"
|
||||
)
|
||||
|
||||
url = "/don_confiao/api/catalogue_images/"
|
||||
image_file = _create_test_image()
|
||||
data = {"product": self.product.id, "image": image_file}
|
||||
response = self.client.post(url, data, format="multipart")
|
||||
self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
|
||||
|
||||
def test_get_catalogue_images_authenticated_non_admin(self):
|
||||
self.user = User.objects.create_user(
|
||||
username="regularuser2",
|
||||
email="regular2@example.com",
|
||||
password="regularpass",
|
||||
)
|
||||
refresh = RefreshToken.for_user(self.user)
|
||||
self.client = APIClient()
|
||||
self.client.credentials(
|
||||
HTTP_AUTHORIZATION=f"Bearer {str(refresh.access_token)}"
|
||||
)
|
||||
|
||||
url = "/don_confiao/api/catalogue_images/"
|
||||
response = self.client.get(url)
|
||||
self.assertEqual(response.status_code, status.HTTP_200_OK)
|
||||
|
||||
def test_delete_catalogue_image_non_admin(self):
|
||||
admin_user = User.objects.create_superuser(
|
||||
username="admin2", email="admin2@example.com", password="adminpass"
|
||||
)
|
||||
admin_refresh = RefreshToken.for_user(admin_user)
|
||||
admin_client = APIClient()
|
||||
admin_client.credentials(
|
||||
HTTP_AUTHORIZATION=f"Bearer {str(admin_refresh.access_token)}"
|
||||
)
|
||||
|
||||
image_file = _create_test_image()
|
||||
create_data = {
|
||||
"product": self.product.id, "image": image_file
|
||||
}
|
||||
create_response = admin_client.post(
|
||||
"/don_confiao/api/catalogue_images/", create_data, format="multipart"
|
||||
)
|
||||
ci_id = create_response.json()["id"]
|
||||
|
||||
regular_user = User.objects.create_user(
|
||||
username="regularuser3",
|
||||
email="regular3@example.com",
|
||||
password="regularpass",
|
||||
)
|
||||
refresh = RefreshToken.for_user(regular_user)
|
||||
self.client = APIClient()
|
||||
self.client.credentials(
|
||||
HTTP_AUTHORIZATION=f"Bearer {str(refresh.access_token)}"
|
||||
)
|
||||
|
||||
response = self.client.delete(
|
||||
f"/don_confiao/api/catalogue_images/{ci_id}/"
|
||||
)
|
||||
self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
|
||||
|
||||
self.assertEqual(CatalogueImage.objects.count(), 1)
|
||||
|
||||
|
||||
class TestCatalogueImageAPI(APITestCase, LoginMixin):
|
||||
def setUp(self):
|
||||
self.login()
|
||||
self.product = Product.objects.create(
|
||||
name="API Test Product", price=100.00
|
||||
)
|
||||
self.product2 = Product.objects.create(
|
||||
name="API Test Product 2", price=200.00
|
||||
)
|
||||
|
||||
def _create_image(self, product=None, width=600, height=400):
|
||||
if product is None:
|
||||
product = self.product
|
||||
image_file = _create_test_image(width=width, height=height)
|
||||
url = "/don_confiao/api/catalogue_images/"
|
||||
data = {"product": product.id, "image": image_file}
|
||||
return self.client.post(url, data, format="multipart")
|
||||
|
||||
def test_list_catalogue_images_empty(self):
|
||||
url = "/don_confiao/api/catalogue_images/"
|
||||
response = self.client.get(url)
|
||||
self.assertEqual(response.status_code, status.HTTP_200_OK)
|
||||
self.assertEqual(response.json(), [])
|
||||
|
||||
def test_create_catalogue_image(self):
|
||||
response = self._create_image()
|
||||
self.assertEqual(response.status_code, status.HTTP_201_CREATED)
|
||||
data = response.json()
|
||||
self.assertIn("id", data)
|
||||
self.assertEqual(data["product"], self.product.id)
|
||||
self.assertIn("image", data)
|
||||
self.assertIn("uploaded_at", data)
|
||||
|
||||
def test_list_catalogue_images(self):
|
||||
self._create_image()
|
||||
self._create_image(product=self.product2)
|
||||
|
||||
url = "/don_confiao/api/catalogue_images/"
|
||||
response = self.client.get(url)
|
||||
self.assertEqual(response.status_code, status.HTTP_200_OK)
|
||||
self.assertEqual(len(response.json()), 2)
|
||||
|
||||
def test_retrieve_catalogue_image(self):
|
||||
create_response = self._create_image()
|
||||
ci_id = create_response.json()["id"]
|
||||
|
||||
url = f"/don_confiao/api/catalogue_images/{ci_id}/"
|
||||
response = self.client.get(url)
|
||||
self.assertEqual(response.status_code, status.HTTP_200_OK)
|
||||
self.assertEqual(response.json()["id"], ci_id)
|
||||
self.assertEqual(response.json()["product"], self.product.id)
|
||||
|
||||
def test_update_catalogue_image(self):
|
||||
create_response = self._create_image()
|
||||
ci_id = create_response.json()["id"]
|
||||
|
||||
new_image = _create_test_image(width=200, height=200, name="updated.png")
|
||||
url = f"/don_confiao/api/catalogue_images/{ci_id}/"
|
||||
response = self.client.put(
|
||||
url,
|
||||
{"product": self.product.id, "image": new_image},
|
||||
format="multipart",
|
||||
)
|
||||
self.assertEqual(response.status_code, status.HTTP_200_OK)
|
||||
|
||||
def test_delete_catalogue_image(self):
|
||||
create_response = self._create_image()
|
||||
ci_id = create_response.json()["id"]
|
||||
|
||||
url = f"/don_confiao/api/catalogue_images/{ci_id}/"
|
||||
response = self.client.delete(url)
|
||||
self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT)
|
||||
|
||||
self.assertEqual(CatalogueImage.objects.count(), 0)
|
||||
|
||||
def test_create_catalogue_image_invalid_product(self):
|
||||
image_file = _create_test_image()
|
||||
url = "/don_confiao/api/catalogue_images/"
|
||||
data = {"product": 99999, "image": image_file}
|
||||
response = self.client.post(url, data, format="multipart")
|
||||
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
|
||||
|
||||
def test_create_catalogue_image_missing_file(self):
|
||||
url = "/don_confiao/api/catalogue_images/"
|
||||
data = {"product": self.product.id}
|
||||
response = self.client.post(url, data, format="multipart")
|
||||
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
|
||||
|
||||
|
||||
class TestCatalogueImageResize(APITestCase, LoginMixin):
|
||||
def setUp(self):
|
||||
self.login()
|
||||
self.product = Product.objects.create(
|
||||
name="Resize Test Product", price=100.00
|
||||
)
|
||||
|
||||
def _create_and_get_image_obj(self, width, height, strict=False,
|
||||
bg_color=(0, 0, 0, 0)):
|
||||
settings_overrides = {
|
||||
"CATALOGUE_IMAGE_WIDTH": 600,
|
||||
"CATALOGUE_IMAGE_HEIGHT": 600,
|
||||
"CATALOGUE_STRICT_DIMENSION": strict,
|
||||
"CATALOGUE_BACKGROUND_IMAGES_RGBA": bg_color,
|
||||
}
|
||||
|
||||
with override_settings(**settings_overrides):
|
||||
image_file = _create_test_image(width=width, height=height)
|
||||
url = "/don_confiao/api/catalogue_images/"
|
||||
data = {"product": self.product.id, "image": image_file}
|
||||
response = self.client.post(url, data, format="multipart")
|
||||
|
||||
self.assertEqual(response.status_code, status.HTTP_201_CREATED)
|
||||
ci_id = response.json()["id"]
|
||||
return CatalogueImage.objects.get(id=ci_id)
|
||||
|
||||
def test_resize_non_strict_mode_landscape(self):
|
||||
ci = self._create_and_get_image_obj(
|
||||
width=800, height=600, strict=False
|
||||
)
|
||||
with Image.open(ci.image.path) as img:
|
||||
self.assertEqual(img.width, 600)
|
||||
expected_height = int(600 * 600 / 800)
|
||||
self.assertEqual(img.height, expected_height)
|
||||
|
||||
def test_resize_non_strict_mode_portrait(self):
|
||||
ci = self._create_and_get_image_obj(
|
||||
width=600, height=800, strict=False
|
||||
)
|
||||
with Image.open(ci.image.path) as img:
|
||||
self.assertEqual(img.width, 600)
|
||||
expected_height = int(800 * 600 / 600)
|
||||
self.assertEqual(img.height, expected_height)
|
||||
|
||||
def test_resize_non_strict_mode_square(self):
|
||||
ci = self._create_and_get_image_obj(
|
||||
width=600, height=600, strict=False
|
||||
)
|
||||
with Image.open(ci.image.path) as img:
|
||||
self.assertEqual(img.width, 600)
|
||||
self.assertEqual(img.height, 600)
|
||||
|
||||
def test_resize_non_strict_no_upscale(self):
|
||||
ci = self._create_and_get_image_obj(
|
||||
width=400, height=300, strict=False
|
||||
)
|
||||
with Image.open(ci.image.path) as img:
|
||||
self.assertEqual(img.width, 400)
|
||||
self.assertEqual(img.height, 300)
|
||||
|
||||
def test_resize_strict_mode_landscape(self):
|
||||
ci = self._create_and_get_image_obj(
|
||||
width=800, height=600, strict=True
|
||||
)
|
||||
with Image.open(ci.image.path) as img:
|
||||
self.assertEqual(img.width, 600)
|
||||
self.assertEqual(img.height, 600)
|
||||
|
||||
def test_resize_strict_mode_portrait(self):
|
||||
ci = self._create_and_get_image_obj(
|
||||
width=600, height=800, strict=True
|
||||
)
|
||||
with Image.open(ci.image.path) as img:
|
||||
self.assertEqual(img.width, 600)
|
||||
self.assertEqual(img.height, 600)
|
||||
|
||||
def test_resize_strict_mode_with_color_background(self):
|
||||
ci = self._create_and_get_image_obj(
|
||||
width=800, height=600, strict=True, bg_color=(255, 255, 255, 255)
|
||||
)
|
||||
with Image.open(ci.image.path) as img:
|
||||
self.assertEqual(img.width, 600)
|
||||
self.assertEqual(img.height, 600)
|
||||
|
||||
@override_settings(CATALOGUE_MAX_UPLOAD_SIZE=1)
|
||||
def test_resize_large_file_rejected(self):
|
||||
image_file = _create_test_image(width=10, height=10)
|
||||
url = "/don_confiao/api/catalogue_images/"
|
||||
data = {"product": self.product.id, "image": image_file}
|
||||
response = self.client.post(url, data, format="multipart")
|
||||
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
|
||||
|
||||
|
||||
class TestProductListingWithImages(APITestCase, LoginMixin):
|
||||
def setUp(self):
|
||||
self.login()
|
||||
self.product = Product.objects.create(
|
||||
name="Product With Images", price=100.00
|
||||
)
|
||||
self.product_no_images = Product.objects.create(
|
||||
name="Product Without Images", price=200.00
|
||||
)
|
||||
|
||||
def test_product_list_includes_catalogue_images_field(self):
|
||||
url = "/don_confiao/api/products/"
|
||||
response = self.client.get(url)
|
||||
self.assertEqual(response.status_code, status.HTTP_200_OK)
|
||||
for product in response.json():
|
||||
self.assertIn("catalogue_images", product)
|
||||
|
||||
def test_product_list_catalogue_images_urls(self):
|
||||
image_file = _create_test_image()
|
||||
CatalogueImage.objects.create(
|
||||
product=self.product, image=image_file
|
||||
)
|
||||
|
||||
url = "/don_confiao/api/products/"
|
||||
response = self.client.get(url)
|
||||
data = response.json()
|
||||
|
||||
product_data = next(
|
||||
p for p in data if p["id"] == self.product.id
|
||||
)
|
||||
self.assertEqual(len(product_data["catalogue_images"]), 1)
|
||||
self.assertTrue(
|
||||
product_data["catalogue_images"][0].endswith(".png")
|
||||
)
|
||||
|
||||
def test_product_list_catalogue_images_multiple(self):
|
||||
img1 = _create_test_image(name="img1.png")
|
||||
img2 = _create_test_image(name="img2.png")
|
||||
CatalogueImage.objects.create(product=self.product, image=img1)
|
||||
CatalogueImage.objects.create(product=self.product, image=img2)
|
||||
|
||||
url = "/don_confiao/api/products/"
|
||||
response = self.client.get(url)
|
||||
data = response.json()
|
||||
|
||||
product_data = next(
|
||||
p for p in data if p["id"] == self.product.id
|
||||
)
|
||||
self.assertEqual(len(product_data["catalogue_images"]), 2)
|
||||
|
||||
def test_product_list_catalogue_images_empty(self):
|
||||
url = "/don_confiao/api/products/"
|
||||
response = self.client.get(url)
|
||||
data = response.json()
|
||||
|
||||
product_data = next(
|
||||
p for p in data if p["id"] == self.product_no_images.id
|
||||
)
|
||||
self.assertEqual(product_data["catalogue_images"], [])
|
||||
|
||||
def test_product_detail_includes_catalogue_images(self):
|
||||
image_file = _create_test_image()
|
||||
CatalogueImage.objects.create(
|
||||
product=self.product, image=image_file
|
||||
)
|
||||
|
||||
url = f"/don_confiao/api/products/{self.product.id}/"
|
||||
response = self.client.get(url)
|
||||
data = response.json()
|
||||
self.assertIn("catalogue_images", data)
|
||||
self.assertEqual(len(data["catalogue_images"]), 1)
|
||||
@@ -0,0 +1,249 @@
|
||||
import json
|
||||
from unittest.mock import patch, MagicMock
|
||||
|
||||
from django.test import TestCase
|
||||
|
||||
from ..models.sales import Sale, SaleLine, CatalogSale, CatalogSaleLine
|
||||
from ..models.customers import Customer
|
||||
from ..models.products import Product
|
||||
from ..services.tryton.client import TrytonSale, TrytonCatalogSale
|
||||
from .Mixins import LoginMixin
|
||||
|
||||
|
||||
class TestSendSalesToTryton(TestCase, LoginMixin):
|
||||
def setUp(self):
|
||||
self.login()
|
||||
|
||||
self.product = Product.objects.create(
|
||||
name="Panela",
|
||||
price=5000,
|
||||
measuring_unit="UNIT",
|
||||
unit_external_id="1",
|
||||
external_id="1",
|
||||
)
|
||||
self.customer = Customer.objects.create(
|
||||
name="Camilo",
|
||||
external_id="1",
|
||||
address_external_id="307",
|
||||
)
|
||||
self.sale = Sale.objects.create(
|
||||
customer=self.customer,
|
||||
date="2024-09-02",
|
||||
payment_method="CASH",
|
||||
description="un comentario",
|
||||
)
|
||||
SaleLine.objects.create(
|
||||
product=self.product,
|
||||
quantity=2,
|
||||
unit_price=3000,
|
||||
sale=self.sale,
|
||||
)
|
||||
SaleLine.objects.create(
|
||||
product=self.product,
|
||||
quantity=3,
|
||||
unit_price=5000,
|
||||
sale=self.sale,
|
||||
)
|
||||
|
||||
self.catalog_sale = CatalogSale.objects.create(
|
||||
customer=self.customer,
|
||||
date="2024-09-02",
|
||||
customer_name="Camilo",
|
||||
customer_phone="3001234567",
|
||||
customer_address="Calle 123",
|
||||
pickup_method="Recogida en tienda",
|
||||
)
|
||||
CatalogSaleLine.objects.create(
|
||||
catalog_sale=self.catalog_sale,
|
||||
product=self.product,
|
||||
quantity=2,
|
||||
unit_price=3000,
|
||||
)
|
||||
CatalogSaleLine.objects.create(
|
||||
catalog_sale=self.catalog_sale,
|
||||
product=self.product,
|
||||
quantity=3,
|
||||
unit_price=5000,
|
||||
)
|
||||
|
||||
@patch("don_confiao.api.sales.get_tryton_client")
|
||||
def test_send_sales_to_tryton(self, mock_get_tryton_client):
|
||||
external_id = "23423"
|
||||
mock_client = MagicMock()
|
||||
mock_client.call.return_value = [external_id]
|
||||
mock_get_tryton_client.return_value = mock_client
|
||||
|
||||
url = "/don_confiao/api/enviar_ventas_a_tryton"
|
||||
response = self.client.post(url)
|
||||
|
||||
self.assertEqual(response.status_code, 200)
|
||||
content = json.loads(response.content.decode("utf-8"))
|
||||
self.assertEqual(
|
||||
content, {"successful": [self.sale.id], "failed": []}
|
||||
)
|
||||
|
||||
updated_sale = Sale.objects.get(id=self.sale.id)
|
||||
self.assertEqual(updated_sale.external_id, external_id)
|
||||
|
||||
mock_get_tryton_client.assert_called_once()
|
||||
|
||||
mock_client.call.assert_called_once()
|
||||
call_args = mock_client.call.call_args
|
||||
method, params = call_args[0]
|
||||
|
||||
self.assertEqual(method, "model.sale.sale.create")
|
||||
|
||||
tryton_context = params[1]
|
||||
self.assertEqual(tryton_context, {"company": 1, "shops": [1]})
|
||||
|
||||
sale_params = params[0][0]
|
||||
self.assertEqual(sale_params["company"], 1)
|
||||
self.assertEqual(sale_params["shipment_address"], "307")
|
||||
self.assertEqual(sale_params["invoice_address"], "307")
|
||||
self.assertEqual(sale_params["currency"], 31)
|
||||
self.assertEqual(sale_params["comment"], "un comentario")
|
||||
self.assertEqual(sale_params["description"], "Metodo pago: CASH")
|
||||
self.assertEqual(sale_params["party"], "1")
|
||||
self.assertEqual(
|
||||
sale_params["reference"], f"don_confiao {self.sale.id}"
|
||||
)
|
||||
self.assertEqual(
|
||||
sale_params["sale_date"],
|
||||
{"__class__": "date", "year": 2024, "month": 9, "day": 2},
|
||||
)
|
||||
self.assertTrue(sale_params["self_pick_up"])
|
||||
|
||||
sale_tryton = TrytonSale(
|
||||
self.sale, SaleLine.objects.filter(sale=self.sale)
|
||||
)
|
||||
self.assertEqual(
|
||||
sale_tryton.build_tryton_comment(), self.sale.description
|
||||
)
|
||||
|
||||
lines_block = sale_params["lines"]
|
||||
self.assertEqual(len(lines_block), 1)
|
||||
self.assertEqual(lines_block[0][0], "create")
|
||||
|
||||
lines = lines_block[0][1]
|
||||
self.assertEqual(len(lines), 2)
|
||||
|
||||
self.assertEqual(lines[0]["product"], "1")
|
||||
self.assertEqual(
|
||||
lines[0]["quantity"],
|
||||
{"__class__": "Decimal", "decimal": "2.00"},
|
||||
)
|
||||
self.assertEqual(lines[0]["type"], "line")
|
||||
self.assertEqual(lines[0]["unit"], "1")
|
||||
self.assertEqual(
|
||||
lines[0]["unit_price"],
|
||||
{"__class__": "Decimal", "decimal": "3000.00"},
|
||||
)
|
||||
|
||||
self.assertEqual(lines[1]["product"], "1")
|
||||
self.assertEqual(
|
||||
lines[1]["quantity"],
|
||||
{"__class__": "Decimal", "decimal": "3.00"},
|
||||
)
|
||||
self.assertEqual(lines[1]["type"], "line")
|
||||
self.assertEqual(lines[1]["unit"], "1")
|
||||
self.assertEqual(
|
||||
lines[1]["unit_price"],
|
||||
{"__class__": "Decimal", "decimal": "5000.00"},
|
||||
)
|
||||
|
||||
@patch("don_confiao.api.sales.get_tryton_client")
|
||||
def test_send_catalog_sales_to_tryton(self, mock_get_tryton_client):
|
||||
external_id = "23423"
|
||||
mock_client = MagicMock()
|
||||
mock_client.call.return_value = [external_id]
|
||||
mock_get_tryton_client.return_value = mock_client
|
||||
|
||||
url = "/don_confiao/api/enviar_catalog_sales_a_tryton"
|
||||
response = self.client.post(url)
|
||||
|
||||
self.assertEqual(response.status_code, 200)
|
||||
content = json.loads(response.content.decode("utf-8"))
|
||||
self.assertEqual(
|
||||
content,
|
||||
{"successful": [self.catalog_sale.id], "failed": []},
|
||||
)
|
||||
|
||||
updated = CatalogSale.objects.get(id=self.catalog_sale.id)
|
||||
self.assertEqual(updated.external_id, external_id)
|
||||
|
||||
mock_get_tryton_client.assert_called_once()
|
||||
|
||||
mock_client.call.assert_called_once()
|
||||
call_args = mock_client.call.call_args
|
||||
method, params = call_args[0]
|
||||
|
||||
self.assertEqual(method, "model.sale.sale.create")
|
||||
|
||||
tryton_context = params[1]
|
||||
self.assertEqual(tryton_context, {"company": 1, "shops": [1]})
|
||||
|
||||
sale_params = params[0][0]
|
||||
self.assertEqual(sale_params["company"], 1)
|
||||
self.assertEqual(sale_params["shipment_address"], "307")
|
||||
self.assertEqual(sale_params["invoice_address"], "307")
|
||||
self.assertEqual(sale_params["currency"], 31)
|
||||
self.assertEqual(sale_params["description"], "Venta de catálogo")
|
||||
self.assertEqual(sale_params["party"], "1")
|
||||
self.assertEqual(
|
||||
sale_params["reference"],
|
||||
f"don_confiao_catalog {self.catalog_sale.id}",
|
||||
)
|
||||
self.assertEqual(
|
||||
sale_params["sale_date"],
|
||||
{"__class__": "date", "year": 2024, "month": 9, "day": 2},
|
||||
)
|
||||
self.assertTrue(sale_params["self_pick_up"])
|
||||
|
||||
expected_comment = (
|
||||
"Cliente: Camilo\n"
|
||||
"Teléfono: 3001234567\n"
|
||||
"Dirección: Calle 123\n"
|
||||
"Método de recogida: Recogida en tienda\n"
|
||||
)
|
||||
self.assertEqual(sale_params["comment"], expected_comment)
|
||||
|
||||
catalog_tryton = TrytonCatalogSale(
|
||||
self.catalog_sale,
|
||||
CatalogSaleLine.objects.filter(
|
||||
catalog_sale=self.catalog_sale
|
||||
),
|
||||
)
|
||||
self.assertEqual(
|
||||
catalog_tryton.build_tryton_comment(), expected_comment
|
||||
)
|
||||
|
||||
lines_block = sale_params["lines"]
|
||||
self.assertEqual(len(lines_block), 1)
|
||||
self.assertEqual(lines_block[0][0], "create")
|
||||
|
||||
lines = lines_block[0][1]
|
||||
self.assertEqual(len(lines), 2)
|
||||
|
||||
self.assertEqual(lines[0]["product"], "1")
|
||||
self.assertEqual(
|
||||
lines[0]["quantity"],
|
||||
{"__class__": "Decimal", "decimal": "2.00"},
|
||||
)
|
||||
self.assertEqual(lines[0]["type"], "line")
|
||||
self.assertEqual(lines[0]["unit"], "1")
|
||||
self.assertEqual(
|
||||
lines[0]["unit_price"],
|
||||
{"__class__": "Decimal", "decimal": "3000.00"},
|
||||
)
|
||||
|
||||
self.assertEqual(lines[1]["product"], "1")
|
||||
self.assertEqual(
|
||||
lines[1]["quantity"],
|
||||
{"__class__": "Decimal", "decimal": "3.00"},
|
||||
)
|
||||
self.assertEqual(lines[1]["type"], "line")
|
||||
self.assertEqual(lines[1]["unit"], "1")
|
||||
self.assertEqual(
|
||||
lines[1]["unit_price"],
|
||||
{"__class__": "Decimal", "decimal": "5000.00"},
|
||||
)
|
||||
222
tienda_ilusion/don_confiao/tests/test_order_summary_public.py
Normal file
222
tienda_ilusion/don_confiao/tests/test_order_summary_public.py
Normal file
@@ -0,0 +1,222 @@
|
||||
from datetime import datetime, timezone
|
||||
|
||||
from django.contrib.auth.models import User
|
||||
from rest_framework import status
|
||||
from rest_framework.test import APIClient, APITestCase
|
||||
|
||||
from ..admin import CatalogSaleAdmin, SaleAdmin
|
||||
from ..models.customers import Customer
|
||||
from ..models.products import Product
|
||||
from ..models.sales import CatalogSale, Sale
|
||||
from ..serializers import CatalogSaleSerializer, SaleSerializer
|
||||
from .Mixins import LoginMixin
|
||||
|
||||
|
||||
class TestOrderSummaryPublic(APITestCase, LoginMixin):
|
||||
def setUp(self):
|
||||
self.product = Product.objects.create(
|
||||
name="Panela", price=5000, measuring_unit="UNIT"
|
||||
)
|
||||
self.customer = Customer.objects.create(
|
||||
name="Camilo", external_id="18"
|
||||
)
|
||||
|
||||
def _create_sale(self):
|
||||
sale = Sale.objects.create(
|
||||
customer=self.customer,
|
||||
date=datetime(2024, 9, 2, tzinfo=timezone.utc),
|
||||
payment_method="CASH",
|
||||
)
|
||||
sale.saleline_set.create(
|
||||
product=self.product, quantity=2, unit_price=3000
|
||||
)
|
||||
return sale
|
||||
|
||||
def _create_catalog_sale(self):
|
||||
catalog_sale = CatalogSale.objects.create(
|
||||
customer=self.customer,
|
||||
date=datetime(2024, 9, 2, tzinfo=timezone.utc),
|
||||
customer_name="Camilo",
|
||||
)
|
||||
catalog_sale.catalogsaleline_set.create(
|
||||
product=self.product, quantity=2, unit_price=3000
|
||||
)
|
||||
return catalog_sale
|
||||
|
||||
def test_sale_has_auto_generated_code(self):
|
||||
sale = self._create_sale()
|
||||
self.assertTrue(sale.code)
|
||||
self.assertEqual(len(sale.code), 32)
|
||||
int(sale.code, 16)
|
||||
|
||||
def test_sale_codes_are_distinct(self):
|
||||
sale1 = self._create_sale()
|
||||
sale2 = self._create_sale()
|
||||
self.assertNotEqual(sale1.code, sale2.code)
|
||||
|
||||
def test_catalog_sale_has_auto_generated_code(self):
|
||||
catalog_sale = self._create_catalog_sale()
|
||||
self.assertTrue(catalog_sale.code)
|
||||
self.assertEqual(len(catalog_sale.code), 32)
|
||||
int(catalog_sale.code, 16)
|
||||
|
||||
def test_public_summary_by_code_without_auth(self):
|
||||
sale = self._create_sale()
|
||||
response = self.client.get(
|
||||
f"/don_confiao/resumen_publico/{sale.code}"
|
||||
)
|
||||
self.assertEqual(response.status_code, status.HTTP_200_OK)
|
||||
data = response.json()
|
||||
self.assertEqual(data["code"], sale.code)
|
||||
self.assertIn("link", data)
|
||||
self.assertTrue(
|
||||
data["link"].endswith(
|
||||
f"/don_confiao/resumen_publico/{sale.code}"
|
||||
)
|
||||
)
|
||||
self.assertEqual(data["type"], "sale")
|
||||
self.assertIn("lines", data)
|
||||
self.assertGreaterEqual(len(data["lines"]), 1)
|
||||
|
||||
def test_public_summary_invalid_code_returns_404(self):
|
||||
response = self.client.get(
|
||||
"/don_confiao/resumen_publico/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
|
||||
)
|
||||
self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
|
||||
|
||||
def test_public_summary_by_query_param(self):
|
||||
sale = self._create_sale()
|
||||
response = self.client.get(
|
||||
"/don_confiao/resumen_publico", {"code": sale.code}
|
||||
)
|
||||
self.assertEqual(response.status_code, status.HTTP_200_OK)
|
||||
self.assertEqual(response.json()["code"], sale.code)
|
||||
|
||||
def test_public_summary_for_catalog_sale(self):
|
||||
catalog_sale = self._create_catalog_sale()
|
||||
response = self.client.get(
|
||||
f"/don_confiao/resumen_publico/{catalog_sale.code}"
|
||||
)
|
||||
self.assertEqual(response.status_code, status.HTTP_200_OK)
|
||||
data = response.json()
|
||||
self.assertEqual(data["code"], catalog_sale.code)
|
||||
self.assertEqual(data["type"], "catalog")
|
||||
|
||||
def test_public_summary_with_duplicate_codes_does_not_500(self):
|
||||
sale1 = self._create_sale()
|
||||
sale2 = self._create_sale()
|
||||
shared = "a" * 32
|
||||
Sale.objects.filter(pk__in=[sale1.pk, sale2.pk]).update(code=shared)
|
||||
response = self.client.get(
|
||||
f"/don_confiao/resumen_publico/{shared}"
|
||||
)
|
||||
self.assertEqual(response.status_code, status.HTTP_200_OK)
|
||||
|
||||
def test_existing_authenticated_summaries_include_code_and_link(self):
|
||||
self.login()
|
||||
sale = self._create_sale()
|
||||
catalog_sale = self._create_catalog_sale()
|
||||
|
||||
response = self.client.get(
|
||||
f"/don_confiao/resumen_compra_json/{sale.id}"
|
||||
)
|
||||
self.assertEqual(response.status_code, status.HTTP_200_OK)
|
||||
data = response.json()
|
||||
self.assertEqual(data["code"], sale.code)
|
||||
self.assertIn("link", data)
|
||||
|
||||
response = self.client.get(
|
||||
f"/don_confiao/resumen_compra_catalogo_json/{catalog_sale.id}"
|
||||
)
|
||||
self.assertEqual(response.status_code, status.HTTP_200_OK)
|
||||
data = response.json()
|
||||
self.assertEqual(data["code"], catalog_sale.code)
|
||||
self.assertIn("link", data)
|
||||
|
||||
def test_fill_codes_sales_endpoint_rewrites_all_codes(self):
|
||||
self.login()
|
||||
sale1 = self._create_sale()
|
||||
sale2 = self._create_sale()
|
||||
old_codes = {sale1.code, sale2.code}
|
||||
|
||||
response = self.client.post("/don_confiao/api/sales/fill_codes/")
|
||||
self.assertEqual(response.status_code, status.HTTP_200_OK)
|
||||
self.assertEqual(response.json()["sales_updated"], 2)
|
||||
|
||||
sale1.refresh_from_db()
|
||||
sale2.refresh_from_db()
|
||||
new_codes = {sale1.code, sale2.code}
|
||||
self.assertNotIn(sale1.code, old_codes)
|
||||
self.assertEqual(len(new_codes), 2)
|
||||
|
||||
def test_fill_codes_catalog_sales_endpoint_rewrites_all_codes(self):
|
||||
self.login()
|
||||
catalog_sale = self._create_catalog_sale()
|
||||
old_code = catalog_sale.code
|
||||
|
||||
response = self.client.post(
|
||||
"/don_confiao/api/catalog_sales/fill_codes/"
|
||||
)
|
||||
self.assertEqual(response.status_code, status.HTTP_200_OK)
|
||||
self.assertEqual(response.json()["catalog_sales_updated"], 1)
|
||||
|
||||
catalog_sale.refresh_from_db()
|
||||
self.assertNotEqual(catalog_sale.code, old_code)
|
||||
|
||||
def test_fill_codes_endpoints_require_authentication(self):
|
||||
response = self.client.post("/don_confiao/api/sales/fill_codes/")
|
||||
self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)
|
||||
|
||||
response = self.client.post(
|
||||
"/don_confiao/api/catalog_sales/fill_codes/"
|
||||
)
|
||||
self.assertEqual(
|
||||
response.status_code, status.HTTP_401_UNAUTHORIZED
|
||||
)
|
||||
|
||||
def test_fill_codes_endpoints_require_admin(self):
|
||||
regular_user = User.objects.create_user(
|
||||
username="regular", password="regularpass"
|
||||
)
|
||||
client = APIClient()
|
||||
client.force_authenticate(user=regular_user)
|
||||
|
||||
response = client.post("/don_confiao/api/sales/fill_codes/")
|
||||
self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
|
||||
|
||||
response = client.post(
|
||||
"/don_confiao/api/catalog_sales/fill_codes/"
|
||||
)
|
||||
self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
|
||||
|
||||
def test_admin_list_display_includes_code(self):
|
||||
self.assertIn("code", SaleAdmin.list_display)
|
||||
self.assertIn("code", CatalogSaleAdmin.list_display)
|
||||
|
||||
def test_sale_serializer_includes_code(self):
|
||||
sale = self._create_sale()
|
||||
data = SaleSerializer(sale).data
|
||||
self.assertIn("code", data)
|
||||
self.assertEqual(data["code"], sale.code)
|
||||
|
||||
def test_catalog_sale_serializer_includes_code(self):
|
||||
catalog_sale = self._create_catalog_sale()
|
||||
data = CatalogSaleSerializer(catalog_sale).data
|
||||
self.assertIn("code", data)
|
||||
self.assertEqual(data["code"], catalog_sale.code)
|
||||
|
||||
def test_sales_list_endpoint_includes_code(self):
|
||||
self.login()
|
||||
sale = self._create_sale()
|
||||
response = self.client.get("/don_confiao/api/sales/")
|
||||
self.assertEqual(response.status_code, status.HTTP_200_OK)
|
||||
item = next(i for i in response.json() if i["id"] == sale.id)
|
||||
self.assertEqual(item["code"], sale.code)
|
||||
|
||||
def test_catalog_sales_list_endpoint_includes_code(self):
|
||||
self.login()
|
||||
catalog_sale = self._create_catalog_sale()
|
||||
response = self.client.get("/don_confiao/api/catalog_sales/")
|
||||
self.assertEqual(response.status_code, status.HTTP_200_OK)
|
||||
item = next(i for i in response.json() if i["id"] == catalog_sale.id)
|
||||
self.assertEqual(item["code"], catalog_sale.code)
|
||||
246
tienda_ilusion/don_confiao/tests/test_store_settings.py
Normal file
246
tienda_ilusion/don_confiao/tests/test_store_settings.py
Normal file
@@ -0,0 +1,246 @@
|
||||
import base64
|
||||
|
||||
from django.contrib.auth.models import User
|
||||
from django.core.files.uploadedfile import SimpleUploadedFile
|
||||
from django.test import override_settings
|
||||
from rest_framework import status
|
||||
from rest_framework.test import APIClient, APITestCase
|
||||
from rest_framework_simplejwt.tokens import RefreshToken
|
||||
|
||||
from ..models.store_settings import StoreSettings
|
||||
from .Mixins import LoginMixin
|
||||
|
||||
URL = "/don_confiao/api/store_settings"
|
||||
|
||||
PNG_1X1 = base64.b64decode(
|
||||
"iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk"
|
||||
"+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg=="
|
||||
)
|
||||
|
||||
|
||||
class TestStoreSettingsModel(APITestCase, LoginMixin):
|
||||
def test_singleton_returns_single_instance(self):
|
||||
first = StoreSettings.get_singleton()
|
||||
second = StoreSettings.get_singleton()
|
||||
self.assertEqual(first.pk, second.pk)
|
||||
self.assertEqual(StoreSettings.objects.count(), 1)
|
||||
|
||||
def test_singleton_created_without_address(self):
|
||||
instance = StoreSettings.get_singleton()
|
||||
self.assertEqual(instance.address, "")
|
||||
|
||||
def test_str(self):
|
||||
instance = StoreSettings.get_singleton()
|
||||
self.assertEqual(str(instance), f"StoreSettings (id={instance.id})")
|
||||
|
||||
|
||||
class TestStoreSettingsAPIPermissions(APITestCase, LoginMixin):
|
||||
def setUp(self):
|
||||
self.url = URL
|
||||
|
||||
def test_get_unauthenticated(self):
|
||||
client = APIClient()
|
||||
response = client.get(self.url)
|
||||
self.assertEqual(response.status_code, status.HTTP_200_OK)
|
||||
|
||||
def test_patch_unauthenticated(self):
|
||||
client = APIClient()
|
||||
response = client.patch(
|
||||
self.url,
|
||||
{"address": "Calle falsa 123"},
|
||||
format="json",
|
||||
)
|
||||
self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)
|
||||
|
||||
def test_patch_non_admin(self):
|
||||
user = User.objects.create_user(
|
||||
username="regularuser",
|
||||
email="regular@example.com",
|
||||
password="regularpass",
|
||||
)
|
||||
refresh = RefreshToken.for_user(user)
|
||||
client = APIClient()
|
||||
client.credentials(
|
||||
HTTP_AUTHORIZATION=f"Bearer {str(refresh.access_token)}"
|
||||
)
|
||||
response = client.patch(
|
||||
self.url,
|
||||
{"address": "Calle falsa 123"},
|
||||
format="json",
|
||||
)
|
||||
self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
|
||||
|
||||
def test_patch_publico(self):
|
||||
user = User.objects.create_user(
|
||||
username="publico",
|
||||
email="publico@example.com",
|
||||
password="publicopass",
|
||||
)
|
||||
user.profile.user_type = "publico"
|
||||
user.profile.save()
|
||||
refresh = RefreshToken.for_user(user)
|
||||
client = APIClient()
|
||||
client.credentials(
|
||||
HTTP_AUTHORIZATION=f"Bearer {str(refresh.access_token)}"
|
||||
)
|
||||
response = client.patch(
|
||||
self.url,
|
||||
{"address": "Calle falsa 123"},
|
||||
format="json",
|
||||
)
|
||||
self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
|
||||
|
||||
|
||||
class TestStoreSettingsAPI(APITestCase, LoginMixin):
|
||||
def setUp(self):
|
||||
self.login()
|
||||
self.url = URL
|
||||
|
||||
def test_get_creates_singleton(self):
|
||||
self.assertEqual(StoreSettings.objects.count(), 0)
|
||||
response = self.client.get(self.url)
|
||||
self.assertEqual(response.status_code, status.HTTP_200_OK)
|
||||
self.assertEqual(StoreSettings.objects.count(), 1)
|
||||
data = response.json()
|
||||
self.assertIn("id", data)
|
||||
self.assertIn("address", data)
|
||||
self.assertIn("latitude", data)
|
||||
self.assertIn("longitude", data)
|
||||
self.assertIn("logo", data)
|
||||
self.assertIn("updated_at", data)
|
||||
|
||||
def test_patch_updates_settings(self):
|
||||
self.client.get(self.url)
|
||||
response = self.client.patch(
|
||||
self.url,
|
||||
{
|
||||
"address": "Carrera 5 # 10-20, Bogotá",
|
||||
"latitude": 4.6097,
|
||||
"longitude": -74.0817,
|
||||
},
|
||||
format="json",
|
||||
)
|
||||
self.assertEqual(response.status_code, status.HTTP_200_OK)
|
||||
data = response.json()
|
||||
self.assertEqual(data["address"], "Carrera 5 # 10-20, Bogotá")
|
||||
self.assertEqual(data["latitude"], 4.6097)
|
||||
self.assertEqual(data["longitude"], -74.0817)
|
||||
|
||||
settings = StoreSettings.objects.get(pk=1)
|
||||
self.assertEqual(settings.address, "Carrera 5 # 10-20, Bogotá")
|
||||
self.assertEqual(settings.latitude, 4.6097)
|
||||
self.assertEqual(settings.longitude, -74.0817)
|
||||
|
||||
def test_patch_partial(self):
|
||||
self.client.get(self.url)
|
||||
response = self.client.patch(
|
||||
self.url,
|
||||
{"address": "Solo dirección"},
|
||||
format="json",
|
||||
)
|
||||
self.assertEqual(response.status_code, status.HTTP_200_OK)
|
||||
settings = StoreSettings.objects.get(pk=1)
|
||||
self.assertEqual(settings.address, "Solo dirección")
|
||||
self.assertIsNone(settings.latitude)
|
||||
|
||||
def test_patch_reuses_singleton(self):
|
||||
self.client.get(self.url)
|
||||
self.client.patch(
|
||||
self.url,
|
||||
{"address": "Primera"},
|
||||
format="json",
|
||||
)
|
||||
self.client.patch(
|
||||
self.url,
|
||||
{"address": "Segunda"},
|
||||
format="json",
|
||||
)
|
||||
self.assertEqual(StoreSettings.objects.count(), 1)
|
||||
|
||||
def test_patch_invalid_coordinates(self):
|
||||
self.client.get(self.url)
|
||||
response = self.client.patch(
|
||||
self.url,
|
||||
{"latitude": "not-a-number"},
|
||||
format="json",
|
||||
)
|
||||
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
|
||||
|
||||
def test_patch_upload_logo(self):
|
||||
self.client.get(self.url)
|
||||
logo = SimpleUploadedFile("logo.png", PNG_1X1, content_type="image/png")
|
||||
response = self.client.patch(
|
||||
self.url,
|
||||
{"logo": logo},
|
||||
format="multipart",
|
||||
)
|
||||
self.assertEqual(response.status_code, status.HTTP_200_OK)
|
||||
data = response.json()
|
||||
self.assertIn("/media/logos/", data["logo"])
|
||||
self.assertTrue(data["logo"].startswith("http"))
|
||||
|
||||
settings = StoreSettings.objects.get(pk=1)
|
||||
self.assertIsNotNone(settings.logo)
|
||||
self.assertTrue(settings.logo.name.startswith("logos/logo"))
|
||||
|
||||
def test_get_returns_absolute_logo_url(self):
|
||||
self.client.get(self.url)
|
||||
logo = SimpleUploadedFile("logo.png", PNG_1X1, content_type="image/png")
|
||||
self.client.patch(self.url, {"logo": logo}, format="multipart")
|
||||
response = self.client.get(self.url)
|
||||
data = response.json()
|
||||
self.assertTrue(data["logo"].startswith("http"))
|
||||
|
||||
def test_patch_logo_non_image(self):
|
||||
self.client.get(self.url)
|
||||
fake = SimpleUploadedFile("logo.txt", b"not an image", content_type="text/plain")
|
||||
response = self.client.patch(
|
||||
self.url,
|
||||
{"logo": fake},
|
||||
format="multipart",
|
||||
)
|
||||
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
|
||||
|
||||
@override_settings(LOGO_MAX_UPLOAD_SIZE=10)
|
||||
def test_patch_logo_too_large(self):
|
||||
self.client.get(self.url)
|
||||
logo = SimpleUploadedFile("logo.png", PNG_1X1, content_type="image/png")
|
||||
response = self.client.patch(
|
||||
self.url,
|
||||
{"logo": logo},
|
||||
format="multipart",
|
||||
)
|
||||
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
|
||||
settings = StoreSettings.objects.get(pk=1)
|
||||
self.assertFalse(settings.logo)
|
||||
|
||||
def test_patch_clear_logo(self):
|
||||
self.client.get(self.url)
|
||||
logo = SimpleUploadedFile("logo.png", PNG_1X1, content_type="image/png")
|
||||
self.client.patch(self.url, {"logo": logo}, format="multipart")
|
||||
response = self.client.patch(
|
||||
self.url,
|
||||
{"logo": None},
|
||||
format="json",
|
||||
)
|
||||
self.assertEqual(response.status_code, status.HTTP_200_OK)
|
||||
data = response.json()
|
||||
self.assertIsNone(data["logo"])
|
||||
settings = StoreSettings.objects.get(pk=1)
|
||||
self.assertFalse(settings.logo)
|
||||
|
||||
def test_patch_upload_logo_keeps_other_fields(self):
|
||||
self.client.get(self.url)
|
||||
logo = SimpleUploadedFile("logo.png", PNG_1X1, content_type="image/png")
|
||||
response = self.client.patch(
|
||||
self.url,
|
||||
{
|
||||
"address": "Avenida Siempre Viva 742",
|
||||
"logo": logo,
|
||||
},
|
||||
format="multipart",
|
||||
)
|
||||
self.assertEqual(response.status_code, status.HTTP_200_OK)
|
||||
settings = StoreSettings.objects.get(pk=1)
|
||||
self.assertEqual(settings.address, "Avenida Siempre Viva 742")
|
||||
self.assertIsNotNone(settings.logo)
|
||||
@@ -2,20 +2,50 @@ from django.urls import path, include
|
||||
from rest_framework.routers import DefaultRouter
|
||||
|
||||
from . import views
|
||||
from . import api_views
|
||||
from .api import (
|
||||
# Catalogue Images
|
||||
CatalogueImageViewSet,
|
||||
# Products
|
||||
ProductView,
|
||||
ProductsFromTrytonView,
|
||||
# Customers
|
||||
CustomerView,
|
||||
CustomersFromTrytonView,
|
||||
# Sales
|
||||
SaleView,
|
||||
CatalogSaleView,
|
||||
SaleSummary,
|
||||
CatalogSaleSummary,
|
||||
PublicSaleSummaryView,
|
||||
SalesForTrytonView,
|
||||
SalesToTrytonView,
|
||||
CatalogSalesToTrytonView,
|
||||
# Payments
|
||||
ReconciliateJarView,
|
||||
ReconciliateJarModelView,
|
||||
PaymentMethodView,
|
||||
SalesForReconciliationView,
|
||||
# Admin
|
||||
AdminCodeValidateView,
|
||||
# Store Settings
|
||||
StoreSettingsView,
|
||||
)
|
||||
|
||||
app_name = "don_confiao"
|
||||
|
||||
router = DefaultRouter()
|
||||
router.register(r"sales", api_views.SaleView, basename="sale")
|
||||
router.register(r"sales", SaleView, basename="sale")
|
||||
router.register(r"catalog_sales", CatalogSaleView, basename="catalog_sale")
|
||||
router.register(r"customers", CustomerView, basename="customer")
|
||||
router.register(r"products", ProductView, basename="product")
|
||||
router.register(
|
||||
r"catalog_sales", api_views.CatalogSaleView, basename="catalog_sale"
|
||||
r"catalogue_images",
|
||||
CatalogueImageViewSet,
|
||||
basename="catalogue_image",
|
||||
)
|
||||
router.register(r"customers", api_views.CustomerView, basename="customer")
|
||||
router.register(r"products", api_views.ProductView, basename="product")
|
||||
router.register(
|
||||
r"reconciliate_jar",
|
||||
api_views.ReconciliateJarModelView,
|
||||
ReconciliateJarModelView,
|
||||
basename="reconciliate_jar",
|
||||
)
|
||||
|
||||
@@ -23,39 +53,60 @@ urlpatterns = [
|
||||
path("productos", views.products, name="products"),
|
||||
path(
|
||||
"resumen_compra_json/<int:id>",
|
||||
api_views.SaleSummary.as_view(),
|
||||
SaleSummary.as_view(),
|
||||
name="purchase_json_summary",
|
||||
),
|
||||
path(
|
||||
"resumen_compra_catalogo_json/<int:id>",
|
||||
CatalogSaleSummary.as_view(),
|
||||
name="catalog_purchase_json_summary",
|
||||
),
|
||||
path(
|
||||
"resumen_publico/<str:code>",
|
||||
PublicSaleSummaryView.as_view(),
|
||||
name="public_purchase_summary",
|
||||
),
|
||||
path(
|
||||
"resumen_publico",
|
||||
PublicSaleSummaryView.as_view(),
|
||||
name="public_purchase_summary_query",
|
||||
),
|
||||
path(
|
||||
"payment_methods/all/select_format",
|
||||
api_views.PaymentMethodView.as_view(),
|
||||
PaymentMethodView.as_view(),
|
||||
name="payment_methods_to_select",
|
||||
),
|
||||
path(
|
||||
"purchases/for_reconciliation",
|
||||
api_views.SalesForReconciliationView.as_view(),
|
||||
SalesForReconciliationView.as_view(),
|
||||
name="sales_for_reconciliation",
|
||||
),
|
||||
path("reconciliate_jar", api_views.ReconciliateJarView.as_view()),
|
||||
path("reconciliate_jar", ReconciliateJarView.as_view()),
|
||||
path("api/", include(router.urls)),
|
||||
path(
|
||||
"api/importar_productos_de_tryton",
|
||||
api_views.ProductsFromTrytonView.as_view(),
|
||||
ProductsFromTrytonView.as_view(),
|
||||
name="products_from_tryton",
|
||||
),
|
||||
path(
|
||||
"api/importar_clientes_de_tryton",
|
||||
api_views.CustomersFromTrytonView.as_view(),
|
||||
CustomersFromTrytonView.as_view(),
|
||||
name="customers_from_tryton",
|
||||
),
|
||||
path(
|
||||
"api/enviar_ventas_a_tryton",
|
||||
api_views.SalesToTrytonView.as_view(),
|
||||
SalesToTrytonView.as_view(),
|
||||
name="send_tryton",
|
||||
),
|
||||
path(
|
||||
"api/admin_code/validate/<code>",
|
||||
api_views.AdminCodeValidateView.as_view(),
|
||||
"api/enviar_catalog_sales_a_tryton",
|
||||
CatalogSalesToTrytonView.as_view(),
|
||||
name="send_catalog_sales_tryton",
|
||||
),
|
||||
path("api/sales/for_tryton", api_views.SalesForTrytonView.as_view()),
|
||||
path(
|
||||
"api/admin_code/validate/<code>",
|
||||
AdminCodeValidateView.as_view(),
|
||||
),
|
||||
path("api/sales/for_tryton", SalesForTrytonView.as_view()),
|
||||
path("api/store_settings", StoreSettingsView.as_view()),
|
||||
]
|
||||
|
||||
@@ -1,3 +1,23 @@
|
||||
from django.contrib import admin
|
||||
from django.contrib.auth.models import User
|
||||
from django.contrib.auth.admin import UserAdmin
|
||||
|
||||
# Register your models here.
|
||||
from .models import UserProfile
|
||||
|
||||
|
||||
class UserProfileInline(admin.StackedInline):
|
||||
model = UserProfile
|
||||
can_delete = False
|
||||
|
||||
|
||||
class CustomUserAdmin(UserAdmin):
|
||||
inlines = [UserProfileInline]
|
||||
|
||||
def get_inline_instances(self, request, obj=None):
|
||||
if not obj:
|
||||
return []
|
||||
return super().get_inline_instances(request, obj)
|
||||
|
||||
|
||||
admin.site.unregister(User)
|
||||
admin.site.register(User, CustomUserAdmin)
|
||||
|
||||
@@ -3,3 +3,6 @@ from django.apps import AppConfig
|
||||
|
||||
class UsersConfig(AppConfig):
|
||||
name = 'users'
|
||||
|
||||
def ready(self):
|
||||
import users.signals # noqa
|
||||
|
||||
25
tienda_ilusion/users/migrations/0001_initial.py
Normal file
25
tienda_ilusion/users/migrations/0001_initial.py
Normal file
@@ -0,0 +1,25 @@
|
||||
# Generated by Django 5.0.6 on 2026-06-22 17:26
|
||||
|
||||
import django.db.models.deletion
|
||||
from django.conf import settings
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
initial = True
|
||||
|
||||
dependencies = [
|
||||
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.CreateModel(
|
||||
name='UserProfile',
|
||||
fields=[
|
||||
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
|
||||
('user_type', models.CharField(choices=[('publico', 'Público'), ('user', 'Usuario'), ('administrator', 'Administrador')], default='user', max_length=20)),
|
||||
('user', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, related_name='profile', to=settings.AUTH_USER_MODEL)),
|
||||
],
|
||||
),
|
||||
]
|
||||
@@ -0,0 +1,24 @@
|
||||
from django.db import migrations
|
||||
|
||||
|
||||
def backfill_user_profiles(apps, schema_editor):
|
||||
User = apps.get_model("auth", "User")
|
||||
UserProfile = apps.get_model("users", "UserProfile")
|
||||
for user in User.objects.all():
|
||||
UserProfile.objects.get_or_create(
|
||||
user=user,
|
||||
defaults={
|
||||
"user_type": "administrator" if user.is_staff else "user",
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('users', '0001_initial'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.RunPython(backfill_user_profiles, migrations.RunPython.noop),
|
||||
]
|
||||
@@ -1,3 +1,19 @@
|
||||
from django.db import models
|
||||
from django.contrib.auth.models import User
|
||||
|
||||
# Create your models here.
|
||||
|
||||
class UserProfile(models.Model):
|
||||
USER_TYPE_CHOICES = [
|
||||
("publico", "Público"),
|
||||
("user", "Usuario"),
|
||||
("administrator", "Administrador"),
|
||||
]
|
||||
user = models.OneToOneField(
|
||||
User, on_delete=models.CASCADE, related_name="profile"
|
||||
)
|
||||
user_type = models.CharField(
|
||||
max_length=20, choices=USER_TYPE_CHOICES, default="user"
|
||||
)
|
||||
|
||||
def __str__(self):
|
||||
return f"{self.user.username} - {self.user_type}"
|
||||
|
||||
@@ -1,13 +1,25 @@
|
||||
from django.contrib.auth.models import User
|
||||
from rest_framework import serializers
|
||||
|
||||
from .models import UserProfile
|
||||
|
||||
|
||||
class UserSerializer(serializers.ModelSerializer):
|
||||
role = serializers.SerializerMethodField()
|
||||
|
||||
class Meta:
|
||||
model = User
|
||||
fields = ('id', 'username', 'email', 'first_name', 'last_name', 'role')
|
||||
fields = (
|
||||
"id",
|
||||
"username",
|
||||
"email",
|
||||
"first_name",
|
||||
"last_name",
|
||||
"role",
|
||||
)
|
||||
|
||||
def get_role(self, obj):
|
||||
return 'administrator' if obj.is_staff else 'user'
|
||||
try:
|
||||
return obj.profile.user_type
|
||||
except UserProfile.DoesNotExist:
|
||||
return "administrator" if obj.is_staff else "user"
|
||||
|
||||
12
tienda_ilusion/users/signals.py
Normal file
12
tienda_ilusion/users/signals.py
Normal file
@@ -0,0 +1,12 @@
|
||||
from django.db.models.signals import post_save
|
||||
from django.dispatch import receiver
|
||||
from django.contrib.auth.models import User
|
||||
|
||||
from .models import UserProfile
|
||||
|
||||
|
||||
@receiver(post_save, sender=User)
|
||||
def create_user_profile(sender, instance, created, **kwargs):
|
||||
if created:
|
||||
user_type = "administrator" if instance.is_staff else "user"
|
||||
UserProfile.objects.create(user=instance, user_type=user_type)
|
||||
@@ -4,6 +4,8 @@ from django.contrib.auth.models import User
|
||||
from rest_framework.test import APIClient
|
||||
from rest_framework_simplejwt.tokens import RefreshToken
|
||||
|
||||
from .models import UserProfile
|
||||
|
||||
|
||||
class MeEndpointTests(TestCase):
|
||||
def setUp(self):
|
||||
@@ -49,7 +51,6 @@ class MeEndpointTests(TestCase):
|
||||
username='regular',
|
||||
email='regular@example.com',
|
||||
password='regularpass',
|
||||
is_staff=False
|
||||
)
|
||||
|
||||
refresh = RefreshToken.for_user(regular_user)
|
||||
@@ -87,6 +88,31 @@ class MeEndpointTests(TestCase):
|
||||
self.assertEqual(response.status_code, 200)
|
||||
self.assertEqual(response.json()['role'], 'administrator')
|
||||
|
||||
def test_publico_user_role_is_publico(self):
|
||||
"""
|
||||
Verifica que un usuario con user_type='publico' recibe role 'publico'.
|
||||
"""
|
||||
publico_user = User.objects.create_user(
|
||||
username='publico',
|
||||
email='publico@example.com',
|
||||
password='publicopass',
|
||||
)
|
||||
profile = UserProfile.objects.get(user=publico_user)
|
||||
profile.user_type = 'publico'
|
||||
profile.save()
|
||||
|
||||
refresh = RefreshToken.for_user(publico_user)
|
||||
access_token = str(refresh.access_token)
|
||||
|
||||
client = APIClient()
|
||||
client.credentials(HTTP_AUTHORIZATION=f'Bearer {access_token}')
|
||||
|
||||
url = reverse('current-user')
|
||||
response = client.get(url)
|
||||
|
||||
self.assertEqual(response.status_code, 200)
|
||||
self.assertEqual(response.json()['role'], 'publico')
|
||||
|
||||
def test_me_endpoint_requires_authentication(self):
|
||||
"""
|
||||
Sin token el endpoint debe devolver 401 Unauthorized.
|
||||
|
||||
Reference in New Issue
Block a user