예제 #1
0
def qrreaded(request, id):
    # if user is not logged in redirect him
    if not request.user.is_authenticated:
        return HttpResponseRedirect(reverse('root'))

    # gets purchase
    try:
        purchase = models.Purchase.objects.filter(id=id).first()
    except:
        return HttpResponse(status=404)

    # if user has no permissions to accept the purchase, gets not found
    if not purchase.is_pending() or request.user not in purchase.shop.admins.all() and \
            request.user.id != purchase.shop.owner.id:
        return HttpResponse(status=404)

    # checks again if the purchase is on day, just in case
    date = timezone.now().date()
    if purchase.is_pending() and purchase.dateTime.date() != date:
        purchase.expire()
        purchase.save()
        return HttpResponseRedirect(reverse('root'))

    # accept the purchase
    purchase.accept()
    purchase.save()

    # count number of purchases accepted from the user
    user = uModels.User.objects.filter(id=purchase.user.id).annotate(
        count=Count('purchase',
                    filter=Q(purchase__status='A',
                             purchase__shop=purchase.shop)))
    return render(request, 'qr.html', {'purchase': purchase, 'user': user})
예제 #2
0
def delete(request, id=None):
    # gets shop from data base
    try:
        shop = Shop.objects.filter(id=id, owner=request.user).first()
    except:
        shop = None

    # redirect if the user has no permissions of this shop
    if not request.user.is_authenticated or not request.user.is_shopAdmin or shop is None:
        return HttpResponseRedirect(reverse('root'))

    # if user confirms, delete shop
    if request.method == 'POST':
        shop.delete()

    else:

        # creates confirmation on delete form
        form = forms.ShopForm(
            instance=shop,
            initial={'map': [float(shop.longitude),
                             float(shop.latitude)]})
        return render(request, 'deleteshopform.html', {
            'form': form,
            'id': id,
            'shop': shop.photo
        })

    return HttpResponseRedirect(reverse('root'))
예제 #3
0
def infoUserPurchase(request, id):
    # if user is not logged in redirect him
    if not request.user.is_authenticated:
        return HttpResponseRedirect(reverse('root'))

    # gets the purchase
    try:
        purchase = models.Purchase.objects.filter(id=id,
                                                  user=request.user).first()
    except:
        return HttpResponse(status=404)

    # checks if the purchase pending is on day, else put it on expired
    date = timezone.now().date()
    if purchase.is_pending() and purchase.dateTime.date() != date:
        purchase.expire()
        purchase.save()

    # makes url for the qr code
    base_url = getattr(settings, 'APP_DOMAIN', 'localhost:8000')
    url = base_url + reverse('qr_read', kwargs={'id': purchase.id})
    return render(request, 'purchasedetailhistory.html', {
        'purchase': purchase,
        'qrurl': url
    })
예제 #4
0
def add_schedule(request, id=None):

    # gets shop from data base
    try:
        shop = Shop.objects.filter(id=id, owner=request.user).first()
    except:
        shop = None

    # redirect if the user has no permissions of this shop
    if not request.user.is_authenticated or not request.user.is_shopAdmin or shop is None:
        return HttpResponseRedirect(reverse('root'))

    # if this is a POST request we need to process the form data
    if request.method == 'POST':

        # create a form instance and populate it with data from the request:
        form = forms.ScheduleForm(request.POST, request.FILES)

        # check whether it's valid:
        if form.is_valid():
            day = form.cleaned_data['day']

            # TODO fix this with query
            # checks if the schedule is not existing or overwriting an existing one
            startHour = form.cleaned_data['startHour']
            endHour = form.cleaned_data['endHour']
            list = Schedule.objects.filter(day=day, shop=shop).all()
            go = True
            for schedule in list:
                if (schedule.startHour <= startHour <= schedule.endHour) or (
                        schedule.startHour <= endHour <= schedule.endHour) or (
                            startHour >= schedule.startHour
                            and endHour <= schedule.endHour) or (
                                startHour <= schedule.startHour
                                and endHour >= schedule.endHour):
                    go = False
            if not go:
                form.add_error(None, "S'està sobreposant amb un altre horari")
            else:
                sch = Schedule(shop=shop,
                               day=day,
                               startHour=startHour,
                               endHour=endHour)
                sch.save()
                return HttpResponseRedirect(
                    reverse('list_schedule', kwargs={'id': id}))

    # if a GET (or any other method) we'll create a blank form
    else:
        form = forms.ScheduleForm()
    return render(request, 'shopform.html', {'form': form, 'id': id})
예제 #5
0
def delete_admin(request, id=None, idA=None):
    # gets shop from data base
    try:
        shop = Shop.objects.filter(id=id, owner=request.user).first()
    except:
        shop = None

    # redirect if the user has no permissions of this shop
    if not request.user.is_authenticated or not request.user.is_shopAdmin or shop is None:
        return HttpResponseRedirect(reverse('root'))

    # remove this admin from the shop
    shop.admins.remove(idA)
    shop.save()
    return HttpResponseRedirect(reverse('list_shop_admins', kwargs={'id': id}))
예제 #6
0
def delete_schedule(request, id=None, idS=None):

    # gets shop from data base
    try:
        shop = Shop.objects.filter(id=id, owner=request.user).first()
    except:
        shop = None

    # redirect if the user has no permissions of this shop
    if not request.user.is_authenticated or not request.user.is_shopAdmin or shop is None:
        return HttpResponseRedirect(reverse('root'))

    # gets schedule by id and deletes it
    schedule = Schedule.objects.filter(id=idS).first()
    schedule.delete()
    return HttpResponseRedirect(reverse('list_schedule', kwargs={'id': id}))
예제 #7
0
def list_admins(request, id=None):
    # gets shop from data base
    try:
        shop = Shop.objects.filter(id=id, owner=request.user).first()
    except:
        shop = None

    # redirect if the user has no permissions of this shop
    if not request.user.is_authenticated or not request.user.is_shopAdmin or shop is None:
        return HttpResponseRedirect(reverse('root'))

    if request.method == 'POST':
        form = forms.AddShopAdminForm(request.POST)

        # check whether it's valid:
        if form.is_valid():
            mail = form.cleaned_data['email']
            u = User.objects.filter(email=mail).first()

            # check if the user exists or has shop admin permissions in order to add the admin
            if u is None or not u.is_shopAdmin or u == request.user:
                form.add_error('email', 'No s\'ha trobat l\'usuari')
            else:
                shop.admins.add(u)
                form = forms.AddShopAdminForm()
    # if a GET (or any other method) we'll create a blank form
    else:
        form = forms.AddShopAdminForm()
    # order the admin list by name
    admin_list = shop.admins.all().order_by('name')
    return render(request, 'adminlist.html', {
        'form': form,
        'admins': admin_list,
        'id': id
    })
예제 #8
0
def userList(request):
    # if user is not logged in redirect him
    if not request.user.is_authenticated:
        return HttpResponseRedirect(reverse('root'))

    # gets the purchase list
    purchaseListAll = models.Purchase.objects.filter(
        user=request.user).order_by('-dateTime')
    purchaseListActive = purchaseListAll.filter(status=models.PCH_PENDING)
    viewAllText = 'Totes'
    viewActiveText = 'Pendents'

    # change the list viewed by pending or all and the button text as well
    list = purchaseListActive
    text = viewAllText
    if request.method == 'POST':
        all = request.POST.get("value", "")
        if all == viewActiveText:
            list = purchaseListActive[:20]
        else:
            text = viewActiveText
            list = purchaseListAll[:20]

    return render(request, 'purchaselistuser.html', {
        'list': list,
        'text': text
    })
예제 #9
0
def modify(request, id=None):
    # gets the shop
    try:
        shop = Shop.objects.filter(id=id, owner=request.user).first()
    except:
        shop = None

    # redirect if the user has no permissions of this shop
    if not request.user.is_authenticated or not request.user.is_shopAdmin or shop is None:
        return HttpResponseRedirect(reverse('root'))

    if request.method == 'POST':

        # create a form instance and populate it with data from the request:
        form = forms.ShopForm(request.POST, request.FILES, instance=shop)

        # check whether it's valid:
        if form.is_valid():
            # gets data from form and save it to the data base
            map = form.cleaned_data['map']
            (lon, lat) = map.split(',')
            shop = form.save()
            shop.longitude = lon
            shop.latitude = lat
            secondaryCategories = form.cleaned_data['secondaryCategories']
            services = form.cleaned_data['services']
            shop.save()
            shop.secondaryCategories.set(secondaryCategories)
            shop.services.set(services)

            return HttpResponseRedirect(reverse('root'))

    # if a GET (or any other method) we'll create a blank form
    else:

        # creates a form with the values of the existent shop
        form = forms.ShopForm(
            instance=shop,
            initial={'map': [float(shop.longitude),
                             float(shop.latitude)]})
    return render(request, 'modifyshopform.html', {
        'form': form,
        'id': id,
        'shop': shop.photo
    })
예제 #10
0
def list(request):
    # if user is already logged, no need to log in
    if not request.user.is_authenticated or not request.user.is_shopAdmin:
        return HttpResponseRedirect(reverse('root'))

    # gets the shops with user as admin or owner
    shopsList = Shop.objects.filter(Q(admins__email=request.user.email) | Q(owner__email=request.user.email))\
        .order_by('name').distinct()
    return render(request, 'shoplist.html', {'shops': shopsList})
예제 #11
0
def info(request, id, time_str):
    # if user is not logged in redirect him
    if not request.user.is_authenticated:
        return HttpResponseRedirect(reverse('root'))

    # gets the shop
    try:
        shop = sModels.Shop.objects.filter(id=id).first()
    except:
        return HttpResponse(status=404)
    if request.method == 'POST':
        # gets the time by the url
        dateTime = timezone.now()
        dateTime_str = dateTime.strftime('%d-%m-%Y-')
        dateTime = dateTime.strptime(dateTime_str + time_str, '%d-%m-%Y-%H:%M')
        dateTimeFuture = dateTime + timezone.timedelta(minutes=shop.meanTime)

        # tries to save the purchase, in case of unique violation redirect to user_list
        try:
            purchase = models.Purchase(shop=shop,
                                       user=request.user,
                                       dateTime=dateTime,
                                       endTime=dateTimeFuture,
                                       status=models.PCH_PENDING)
            purchase.save()
            return HttpResponseRedirect(
                reverse('purchase', kwargs={'id': purchase.id}))
        except IntegrityError:
            pass

    # order schedules of the shop by day and startHour
    schedule = shop.schedule.all().order_by('day', 'startHour')
    return render(request, 'purchasedetail.html', {
        'shop': shop,
        'time': time_str,
        'schedule': schedule
    })
예제 #12
0
def list_schedule(request, id=None):

    # gets shop from data base
    try:
        shop = Shop.objects.filter(id=id, owner=request.user).first()
    except:
        shop = None

    # redirect if the user has no permissions of this shop
    if not request.user.is_authenticated or not request.user.is_shopAdmin or shop is None:
        return HttpResponseRedirect(reverse('root'))

    # gets the schedules from the shop
    scheduleList = Schedule.objects.filter(shop=shop).order_by(
        'day', 'startHour')
    return render(request, 'schedulelist.html', {
        'schedules': scheduleList,
        'id': id
    })
예제 #13
0
def show(request, id=None):
    # gets the shop from the data base
    try:
        shop = Shop.objects.filter(id=id, owner=request.user).first()
        if shop is None:
            shop = Shop.objects.filter(id=id, admins=request.user).first()
    except:
        shop = None

    # if user has no permissions in this shop redirect him to root
    if not request.user.is_authenticated or not request.user.is_shopAdmin or shop is None:
        return HttpResponseRedirect(reverse('root'))

    # orders the schedule by day and hour
    schedule = shop.schedule.all().order_by('day', 'startHour')

    return render(request, 'shopview.html', {
        'shop': shop,
        'schedule': schedule
    })
예제 #14
0
def add(request):
    # if user is already logged, no need to log in
    if not request.user.is_authenticated or not request.user.is_shopAdmin:
        return HttpResponseRedirect(reverse('root'))

    # if this is a POST request we need to process the form data
    if request.method == 'POST':

        # create a form instance and populate it with data from the request:
        form = forms.ShopForm(request.POST, request.FILES)

        # check whether it's valid:
        if form.is_valid():

            CIF = form.cleaned_data['CIF']
            name = form.cleaned_data['name']

            # checks if this shop CIF already exists
            if not Shop.objects.filter(CIF=CIF, name=name).first() is None:
                form.add_error('CIF', 'Ja existeix aquesta botiga')
                return render(request, 'shopform.html', {'form': form})

            # gets all data from the form
            meanTime = form.cleaned_data['meanTime']
            secondaryCategories = form.cleaned_data['secondaryCategories']
            services = form.cleaned_data['services']
            photo = form.cleaned_data['photo']
            description = form.cleaned_data['description']
            map = form.cleaned_data['map']
            (lon, lat) = map.split(',')

            # creates the new shop with the form data and sets categories
            shop = Shop(CIF=CIF,
                        name=name,
                        meanTime=meanTime,
                        latitude=lat,
                        longitude=lon,
                        owner=request.user,
                        photo=photo,
                        description=description)
            shop.save()
            shop.secondaryCategories.set(secondaryCategories)
            shop.services.set(services)

            for day in SCH_DAYS:
                if day[0] < 5:
                    startHour = timezone.now().replace(hour=9,
                                                       minute=00).time()
                    endHour = timezone.now().replace(hour=14, minute=00).time()

                    sch = Schedule(shop=shop,
                                   day=day[0],
                                   startHour=startHour,
                                   endHour=endHour)
                    sch.save()

                    startHour = timezone.now().replace(hour=15,
                                                       minute=00).time()
                    endHour = timezone.now().replace(hour=18, minute=00).time()

                    sch2 = Schedule(shop=shop,
                                    day=day[0],
                                    startHour=startHour,
                                    endHour=endHour)
                    sch2.save()

            return HttpResponseRedirect(reverse('root'))

    # if a GET (or any other method) we'll create a blank form
    else:
        form = forms.ShopForm()
    return render(request, 'shopform.html', {'form': form})
예제 #15
0
def list(request):
    # if user is not logged in redirect him
    if not request.user.is_authenticated:
        return HttpResponseRedirect(reverse('root'))
    shopsList = []
    time_str = ''
    llista = False
    if request.method == 'POST':

        form = forms.FilterForm(request.POST)

        if form.is_valid():
            location = form.cleaned_data['location']

            # checks if the location data is in correct format and gets the latitude and longitude
            if location.find(',') != -1:
                (latitude, longitude) = location.split(', ')
            else:
                latitude = 0
                longitude = 0
            (latitude, longitude) = (float(latitude), float(longitude))
            category = form.cleaned_data['category']
            service = form.cleaned_data['service']

            # gets the hour from form and adds the current day
            time = form.cleaned_data['time']
            time_str = time.strftime('%H:%M')
            dateTime = timezone.now()
            dateTime_str = dateTime.strftime('%d-%m-%Y-')
            dateTime = dateTime.strptime(dateTime_str + time_str,
                                         '%d-%m-%Y-%H:%M')
            todayDay = timezone.now().weekday()

            # filters if there's a shop open in this hour
            shopsList = sModels.Schedule.objects.filter(day=todayDay,
                                                        startHour__lte=time,
                                                        endHour__gt=time)

            # filters by search by category and services
            if service and category:
                shopsList = shopsList.filter(
                    shop__secondaryCategories__primary__in=category,
                    shop__services__in=service)
            elif service:
                shopsList = shopsList.filter(shop__services__in=service)
            elif category:
                shopsList = shopsList.filter(
                    shop__secondaryCategories__primary__in=category)

            # orders by the nearest-lessOccupied shops and filters by nearest ones, gets 20 of them in order for the
            # user to have a good experience
            shopsList = shopsList.annotate(distance=(Func((F('shop__latitude') -
                                                           Cast(latitude, DecimalField())) * 111000,
                                                          function='ABS') +
                                                     Func((F('shop__longitude') -
                                                           Cast(longitude, DecimalField())) * 111000,
                                                          function='ABS')) / 70).filter(distance__lt=60) \
                                 .annotate(ocupacio=Count('shop__purchase',
                                                          filter=Q(shop__purchase__dateTime__lte=dateTime,
                                                                   shop__purchase__endTime__gt=dateTime)),
                                           Cpoints=Cast(F('ocupacio') + 1, DecimalField()) * F('distance')) \
                                 .order_by('Cpoints')[:20]
            llista = True
    else:
        form = forms.FilterForm()
    if shopsList is None:
        shopsList = []
    return render(request, 'purcahselist.html', {
        'shops': shopsList,
        'form': form,
        'time': time_str,
        'llista': llista
    })