Merge branch 'main' of ssh://gitea.onecluster.org:6666/OneTeam/don_confiao
This commit is contained in:
@@ -1,9 +1,12 @@
|
||||
from django.shortcuts import render
|
||||
from django.http import HttpResponse, JsonResponse
|
||||
from django.http import HttpResponse, HttpResponseRedirect, JsonResponse
|
||||
from django.template import loader
|
||||
|
||||
from .models import Sale
|
||||
from .models import Sale, Product, ProductCategory
|
||||
from .forms import ImportProductsForm
|
||||
|
||||
import csv
|
||||
import io
|
||||
|
||||
def index(request):
|
||||
return render(request, 'don_confiao/index.html')
|
||||
@@ -28,19 +31,54 @@ def purchases(request):
|
||||
|
||||
|
||||
def products(request):
|
||||
products = [
|
||||
{
|
||||
"name": "Aceite de Coco Artesanal 500ml",
|
||||
"price_list": 50000,
|
||||
"uom": "Unit",
|
||||
"category": "Aceites"
|
||||
},
|
||||
{
|
||||
"name": "Cafe 500ml",
|
||||
"price_list": 14000,
|
||||
"uom": "Unit",
|
||||
"category": "Cafes"
|
||||
},
|
||||
]
|
||||
return JsonResponse(
|
||||
products, safe=False)
|
||||
rproducts = []
|
||||
products = Product.objects.all()
|
||||
for product in products:
|
||||
rproduct = {
|
||||
"name": product.name,
|
||||
"price_list": product.price,
|
||||
"uom": product.measuring_unit,
|
||||
"categories": [c.name for c in product.categories.all()]
|
||||
}
|
||||
rproducts.append(rproduct)
|
||||
|
||||
return JsonResponse(rproducts, safe=False)
|
||||
|
||||
|
||||
def import_products(request):
|
||||
if request.method == "POST":
|
||||
form = ImportProductsForm(request.POST, request.FILES)
|
||||
if form.is_valid():
|
||||
handle_import_products_file(request.FILES["csv_file"])
|
||||
return HttpResponseRedirect("productos")
|
||||
else:
|
||||
form = ImportProductsForm()
|
||||
return render(
|
||||
request,
|
||||
"don_confiao/import_products.html",
|
||||
{'form': form}
|
||||
)
|
||||
|
||||
def _categories_from_csv_string(categories_string, separator="&"):
|
||||
categories = categories_string.split(separator)
|
||||
clean_categories = [c.strip() for c in categories]
|
||||
return [_category_from_name(category) for category in clean_categories]
|
||||
|
||||
def _category_from_name(name):
|
||||
return ProductCategory.objects.get_or_create(name=name)[0]
|
||||
|
||||
def handle_import_products_file(csv_file):
|
||||
data = io.StringIO(csv_file.read().decode('utf-8'))
|
||||
reader = csv.DictReader(data, quotechar='"')
|
||||
for row in reader:
|
||||
product, created = Product.objects.update_or_create(
|
||||
name=row['producto'],
|
||||
defaults={
|
||||
'price': row['precio'],
|
||||
'measuring_unit': row['unidad']
|
||||
}
|
||||
)
|
||||
categories = _categories_from_csv_string(row["categorias"])
|
||||
product.categories.clear()
|
||||
for category in categories:
|
||||
product.categories.add(category)
|
||||
|
||||
Reference in New Issue
Block a user