add basic product search
This commit is contained in:
69
products/views.py
Normal file
69
products/views.py
Normal file
@ -0,0 +1,69 @@
|
||||
from django.http import HttpResponseRedirect, HttpResponse, JsonResponse
|
||||
from django.shortcuts import render, get_object_or_404
|
||||
from django.views.decorators.csrf import csrf_exempt
|
||||
from django.views.decorators.http import require_http_methods
|
||||
|
||||
import json
|
||||
import logging
|
||||
import re
|
||||
|
||||
from account.decorators import login_required
|
||||
|
||||
from .models import Product
|
||||
from procat2.models import Season, Region
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
|
||||
@csrf_exempt
|
||||
@login_required
|
||||
@require_http_methods(["POST"])
|
||||
def search_products(request):
|
||||
body = request.body
|
||||
if not body or len(body) < 1:
|
||||
return HttpResponse('Bad request: no data', status=400)
|
||||
|
||||
data = json.loads(body.decode('utf-8'))
|
||||
|
||||
# TODO enable someday, when product data includes them
|
||||
# season_id = data.get('season')
|
||||
# if not season_id or len(season_id) < 1:
|
||||
# return HttpResponse('Bad request: no season id', status=400)
|
||||
# season = Season.objects.get(id=season_id)
|
||||
# if not season:
|
||||
# return HttpResponse('Bad request: no season found', status=400)
|
||||
|
||||
# region_id = data.get('region')
|
||||
# if not region_id or len(region_id) < 1:
|
||||
# return HttpResponse('Bad request: no region id', status=400)
|
||||
# region = Region.objects.get(id=region_id)
|
||||
# if not region:
|
||||
# return HttpResponse('Bad request: no region found', status=400)
|
||||
|
||||
text = data.get('text')
|
||||
ids = Product.find_sap_ids(text)
|
||||
log.info('found ids %s in %s', ids, text)
|
||||
|
||||
prods = []
|
||||
missing = []
|
||||
|
||||
if ids:
|
||||
search_prods = Product.objects.filter(sap__in=ids).distinct('sap')
|
||||
# TODO: maybe someday
|
||||
#.filter(sap__in=ids, season=season, region=region)
|
||||
|
||||
# fix product order to match input ids and find missing ids
|
||||
prod_dict = dict([(p.sap, p) for p in search_prods])
|
||||
|
||||
for i in ids:
|
||||
if prod_dict.get(i):
|
||||
prods.append(prod_dict[i])
|
||||
else:
|
||||
missing.append(i)
|
||||
|
||||
out = {
|
||||
'found': [p.serialize() for p in prods],
|
||||
'missing': missing,
|
||||
}
|
||||
|
||||
return JsonResponse(out)
|
||||
Reference in New Issue
Block a user