Esempio n. 1
0
def signup(request):
    if request.method != 'POST':
        return HttpResponse(Helpers.create_json_output(Helpers.StatusCodes.NotPostRequest, ''))

    phoneNumber =  request.POST.get('phoneNumber', False)

    # validation
    if not phoneNumber or len(phoneNumber) != 10 or not phoneNumber.isdigit():
        Helpers.logger.debug('Invalid phoneNumber {0}'.format(phoneNumber))
        return HttpResponse(Helpers.create_json_output(Helpers.StatusCodes.InvalidPhoneNum, phoneNumber))
    
    # check whether the phonenumber is already signed-up
    # TODO - can a phonenumber be seller as well as user ??
    try:
        row = Seller.models.Sellers.objects.get(sellerPrimaryPhone=phoneNumber)
        # get is successful
        return HttpResponse(Helpers.create_json_output(Helpers.StatusCodes.PhoneNumAlreadyExists, phoneNumber))
    except Seller.models.Sellers.MultipleObjectsReturned:
        # Alert: shouldn't come here
        return HttpResponse(Helpers.create_json_output(Helpers.StatusCodes.PhoneNumAlreadyExists, phoneNumber))
    except (Seller.models.Sellers.DoesNotExist):
        pass
    
    now = timezone.now()
    delta = datetime.timedelta(seconds=Settings.OTP_VALID_TIME_SECONDS)

    # get random otp

    otpValue = str(random.randint(10000, 99999))
    Helpers.logger.debug('Generated optValue {0}'.format(otpValue))


    # we maintain only single row per phonenumber - invariant
    # check if otp already exist and valid, reuse
    # already exists but invalid, create new 
    # doesn't exists, create new
    try:
        row = Seller.models.SellerOTPMappings.objects.get(phoneNumber=phoneNumber)
        # check if the found has expired
        if row.expiaryDate < now:
            # update new
            row.expiaryDate = now + delta
            row.otpValue = otpValue
            row.save()
            Helpers.logger.debug('Otp exists but expired, updating to new optValue {0}'.format(otpValue))
        else:
            # already exists and valid no need to update
            otpValue = row.otpValue
            Helpers.logger.debug('Otp exists, not expired, reusing optValue {0}'.format(otpValue))
            

    except Seller.models.SellerOTPMappings.DoesNotExist:
        # create new 
        Seller.models.SellerOTPMappings.objects.create(phoneNumber = phoneNumber, otpValue=otpValue, expiaryDate=now + delta)
        Helpers.logger.debug('Otp doesnot exists, using optValue {0}'.format(otpValue))

    # send otp
    # TODO - for now use simple return, we will use SMS api

    return HttpResponse(Helpers.create_json_output(Helpers.StatusCodes.Success, {'otpValue': otpValue }))
Esempio n. 2
0
def seller_view_details(request):
    if request.method != 'GET':
        return HttpResponse(Helpers.create_json_output(Helpers.StatusCodes.NotGetRequest, ''))


    if not Helpers.validate_seller_session(request):
        return HttpResponse(Helpers.create_json_output(Helpers.StatusCodes.InvalidSellerSession, ''))

    sellerId = request.session['sellerId'].id

   

    skip = request.GET.get('skip', False)

    if not skip:
        skip = 0

    else:
        try:
            skip = int(skip)
        except ValueError:
            skip = 0



    # we already have head message, only has to retrive response

    messages = Bargain.models.MessageBoxThreads.objects.filter((Q(toId=sellerId) | Q(fromId=sellerId))).order_by('timestamp').reverse()[skip:skip+20]

    return HttpResponse(Helpers.create_json_output(Helpers.StatusCodes.Success, { 'messages': Helpers.jsonizeDjangoObject(messages)}))
Esempio n. 3
0
def product_search(request):

    if request.method != 'GET':
        return HttpResponse(Helpers.create_json_output(Helpers.StatusCodes.NotGetRequest, ''))

    if not Helpers.validate_user_session(request):
        return HttpResponse(Helpers.create_json_output(Helpers.StatusCodes.InvalidUserSession, ''))

    query_string = ''

    found_entries = None
    if ('q' in request.GET) and request.GET['q'].strip():
        query_string = request.GET['q']
        
        entry_query = get_query(query_string, ['productName'])

        try:
            # Search based on average rating
            found_entries = Products.objects.filter(entry_query).order_by('-productAvgRating')
                    
        except Products.DoesNotExist:
            return HttpResponse(Helpers.create_json_output(Helpers.StatusCodes.NoProductsFound, ''))
        
        
     
    entries = []
    for results in found_entries :
        entries.append(results.productName)

    return HttpResponse(Helpers.create_json_output(Helpers.StatusCodes.Success, entries))
Esempio n. 4
0
def view_summary(request):
    if request.method != 'GET':
        return HttpResponse(Helpers.create_json_output(Helpers.StatusCodes.NotGetRequest, ''))


    if not Helpers.validate_user_session(request):
        return HttpResponse(Helpers.create_json_output(Helpers.StatusCodes.InvalidUserSession, ''))

    userId = request.session.get('userId').id

    messages = Bargain.models.MessageBox.objects.filter(userId=userId).order_by('recentResponseTimestamp').reverse()


    skip = request.GET.get('skip', False)

    if not skip:
        skip = 0

    else:
        try:
            skip = int(skip)
        except ValueError:
            skip = 0

    return HttpResponse(Helpers.create_json_output(Helpers.StatusCodes.Success, {'messages' : Helpers.jsonizeDjangoObject(messages[skip: skip + Helpers.Constants.numMesssagesToReturn])}))
Esempio n. 5
0
def login(request):
    if request.method != 'POST':
        return HttpResponse(Helpers.create_json_output(Helpers.StatusCodes.NotPostRequest, ''))

    password = request.POST.get('password', False)
    phoneNumber =  request.POST.get('phoneNumber', False)

    # we share the otp with user as secret, only the users
    # who have correct otp and phonenumber match and valid
    # opt are allowed to add password
    
    # validation
    if not phoneNumber or len(phoneNumber) != 10 or not phoneNumber.isdigit():
        Helpers.logger.debug('Invalid phoneNumber {0}'.format(phoneNumber))
        return HttpResponse(Helpers.create_json_output(Helpers.StatusCodes.InvalidPhoneNum, phoneNumber))

    if not password or len(password) > 15 or not re.match(Settings.PASSWORD_REGEX_PATTERN, password):
        return HttpResponse(Helpers.create_json_output(Helpers.StatusCodes.InvalidPassword, ''))

    appId = request.POST.get('appId', False)

    if not appId:
        return HttpResponse(Helpers.create_json_output(Helpers.StatusCodes.InvalidAppId, appId))

    now = timezone.now()

    # create sha512
    hashObj = hashlib.sha512()
    hashObj.update(password)
    hashObj.update(phoneNumber)
    hashObj.update(Settings.SECRET_KEY)
    hash = hashObj.hexdigest()

    try:
        row = Seller.models.Sellers.objects.get(sellerPrimaryPhone=phoneNumber, sellerPasswordHash=hash)
        # seller name is valid
        row.sellerAppId = appId
        row.save()


    except Seller.models.Sellers.DoesNotExist:

        Helpers.logger.debug('Invalid seller name or password {0} {1}'.format(phoneNumber, password))
        return HttpResponse(Helpers.create_json_output(Helpers.StatusCodes.InvalidUsernamePassword, ''))

    # create session here 
    response = HttpResponse(Helpers.create_json_output(Helpers.StatusCodes.Success, ''))
    
    Helpers.create_seller_session(request, phoneNumber, row.id)

    return response
Esempio n. 6
0
def close(request):
    if request.method != 'POST':
        return HttpResponse(Helpers.create_json_output(Helpers.StatusCodes.NotPostRequest, ''))
    
    if not Helpers.validate_user_session(request):
        return HttpResponse(Helpers.create_json_output(Helpers.StatusCodes.InvalidUserSession, ''))

    messageId = request.POST.get('messageId', False)

    try:
        message = Bargain.models.MessageBox.objects.get(id=messageId)
    except ObjectDoesNotExist:
        return HttpResponse(Helpers.create_json_output(Helpers.StatusCodes.InvalidMessageId, ''))


    user = request.session.get('userId')
    if message.userId != user.id:
        return HttpResponse(Helpers.create_json_output(Helpers.StatusCodes.InvalidMessageId, {'notOwner' : messageId }))
    

    
    message.isActive = False

    message.save()

    return HttpResponse(Helpers.create_json_output(Helpers.StatusCodes.Success, {'deletedMessageId': messageId}))
Esempio n. 7
0
def signup_optvalidation(request):
    if request.method != 'POST':
        return HttpResponse(Helpers.create_json_output(Helpers.StatusCodes.NotPostRequest, ''))
    
    phoneNumber =  request.POST.get('phoneNumber', False)
    otpValue = request.POST.get('otpValue', False)

    # validation
    if not phoneNumber or len(phoneNumber) != 10 or not phoneNumber.isdigit():
        Helpers.logger.debug('Invalid phoneNumber {0}'.format(phoneNumber))
        return HttpResponse(Helpers.create_json_output(Helpers.StatusCodes.InvalidPhoneNum, phoneNumber))

    if not  otpValue or len(otpValue) != 5 or not otpValue.isdigit():
        Helpers.logger.debug('Invalid otpValue {0}'.format(otpValue))
        return HttpResponse(Helpers.create_json_output(Helpers.StatusCodes.InvalidOtpValue, otpValue))

    now = timezone.now()
    
    try:
        row = Seller.models.SellerOTPMappings.objects.get(phoneNumber=phoneNumber)
        # check if opt is correct and valid
        if row.expiaryDate > now and row.otpValue == otpValue:
            Helpers.logger.debug('Otp exists and valid {0}'.format(otpValue))
            return HttpResponse(Helpers.create_json_output(Helpers.StatusCodes.Success, otpValue))
        else:
            # already exists and valid no need to update
            Helpers.logger.debug('Otp exists, but invalid {0} expirary {1} now {2}'.format(otpValue, row.expiaryDate, now))  
            return HttpResponse(Helpers.create_json_output(Helpers.StatusCodes.OtpValidationFailed, {'otpValue': otpValue}))          


    except Seller.models.SellerOTPMappings.DoesNotExist:
        # create new 
        Helpers.logger.debug('Otp doesnot exists {0}'.format(otpValue))
        return HttpResponse(Helpers.create_json_output(Helpers.StatusCodes.OtpValidationFailed, otpValue))
Esempio n. 8
0
def view_details(request):
    if request.method != 'GET':
        return HttpResponse(Helpers.create_json_output(Helpers.StatusCodes.NotGetRequest, ''))


    if not Helpers.validate_user_session(request):
        return HttpResponse(Helpers.create_json_output(Helpers.StatusCodes.InvalidUserSession, ''))

    userId = request.session.get('userId').id

    messageId = request.GET.get('messageId', False)

    if not messageId:
        return HttpResponse(Helpers.create_json_output(Helpers.StatusCodes.InvalidMessageId, {'messageId': messageId}))


    try:
        messageId = int(messageId)
    except valueError:
        return HttpResponse(Helpers.create_json_output(Helpers.StatusCodes.InvalidMessageId, {'messageId': messageId}))



    # we already have head message, only has to retrive response

    messages = Bargain.models.MessageBoxThreads.objects.filter(Q(messageId=messageId) & (Q(toId=userId) | Q(fromId=userId))).order_by('timestamp').reverse()

    return HttpResponse(Helpers.create_json_output(Helpers.StatusCodes.Success, { 'messages': Helpers.jsonizeDjangoObject(messages)}))
Esempio n. 9
0
def product_specs(request):

     # Validate if its a GET request 
     if request.method != 'GET':
        return HttpResponse(Helpers.create_json_output(Helpers.StatusCodes.NotGetRequest, ''))
    
     # Allow only if the user session is active.
     if not Helpers.validate_user_session(request):
        return HttpResponse(Helpers.create_json_output(Helpers.StatusCodes.InvalidUserSession, ''))
     
     productId = request.GET.get('productId')

     # Validate the product ID
     if not productId or not productId.isdigit():
        return HttpResponse(Helpers.create_json_output(Helpers.StatusCodes.InvalidProductId, productId))

     try:
        product = Products.objects.get(id = productId)

     except Products.DoesNotExist:
        return HttpResponse(Helpers.create_json_output(Helpers.StatusCodes.InvalidProductId, productId))

     
     try :
        brand = ProductBrands.objects.get(id = product.productBrandId_id)

     except ProductBrands.DoesNotExist:
         return HttpResponse(Helpers.create_json_output(Helpers.StatusCodes.InvalidBrandId, { "BrandId": product.productBrandId_id } ))

     # Populate Product Name and Brand Name since they are available at this point

     allDetailsDict = dict()
     allDetailsDict['Product Name'] = product.productName
     allDetailsDict['Brand Name']   = brand.brandName

     # Filter to fetch multiple objects as opposed to get
     try :
         specs = ProductSpecs.objects.filter(productId_id=productId)

     except ProductSpecs.DoesNotExist :
         return HttpResponse(Helpers.create_json_output(Helpers.StatusCodes.NoSpecsFound, ''))

     # Iterate all Key Value pairs for this product and display the specs
     for spec in specs :
        allDetailsDict[spec.key] =  str(spec.value)
        
     return HttpResponse(Helpers.create_json_output(Helpers.StatusCodes.Success, allDetailsDict))
Esempio n. 10
0
def logout(request):
    if request.method != 'GET':
        return HttpResponse(Helpers.create_json_output(Helpers.StatusCodes.NotGetRequest, ''))

    if not Helpers.validate_seller_session(request):
        return HttpResponse(Helpers.create_json_output(Helpers.StatusCodes.InvalidSellerSession, ''))

    Helpers.delete_seller_session(request)

    return HttpResponse(Helpers.create_json_output(Helpers.StatusCodes.Success, 'logged out'))
Esempio n. 11
0
def get_query(query_string, search_fields):
    ''' Returns a query, that is a combination of Q objects. That combination
        aims to search keywords within a model by testing the given search fields.
    '''
    query = None # Query to search for every search term        
    terms = Helpers.normalize_query(query_string)
    for term in terms:
        or_query = None # Query to search for a given term in each field
        for field_name in search_fields:
            q = Q(**{"%s__icontains" % field_name: term})
            if or_query is None:
                or_query = q
            else:
                or_query = or_query | q
        if query is None:
            query = or_query
        else:
            query = query & or_query
    return query
Esempio n. 12
0
def rate_product(request):
    
    if request.method != 'POST':
        return HttpResponse(Helpers.create_json_output(Helpers.StatusCodes.NotPostRequest, ''))
    
    if not Helpers.validate_user_session(request):
        return HttpResponse(Helpers.create_json_output(Helpers.StatusCodes.InvalidUserSession, ''))


    productId = request.POST.get('productId', False)

    if not productId or not productId.isdigit():
        return HttpResponse(Helpers.create_json_output(Helpers.StatusCodes.InvalidProductId, productId))


    ratingVal = request.POST.get('ratingVal', False)

    if not ratingVal or not ratingVal.isdigit():
        return HttpResponse(Helpers.create_json_output(Helpers.StatusCodes.InvalidRatingValue, ratingVal))

    ratingVal = int(ratingVal)
    productId = int(productId)
    
    if ratingVal < 0 or ratingVal > 5:
        return HttpResponse(Helpers.create_json_output(Helpers.StatusCodes.InvalidRatingValue, ratingVal))


    try:
        product = Products.objects.get(id = productId)

    except Products.DoesNotExist:
        return HttpResponse(Helpers.create_json_output(Helpers.StatusCodes.InvalidProductId, productId))


    # session is validated, safe to take userId from session
    ProductRatings.objects.create(productId = product, userId = request.session['userId'], ratingVal = ratingVal)
    

    return HttpResponse(Helpers.create_json_output(Helpers.StatusCodes.Success, ''))
Esempio n. 13
0
def review_product(request):
    if request.method != 'POST':
        return HttpResponse(Helpers.create_json_output(Helpers.StatusCodes.NotPostRequest, ''))
    
    if not Helpers.validate_user_session(request):
        return HttpResponse(Helpers.create_json_output(Helpers.StatusCodes.InvalidUserSession, ''))


    productId = request.POST.get('productId', False)

    if not productId or not productId.isdigit():
        return HttpResponse(Helpers.create_json_output(Helpers.StatusCodes.InvalidProductId, productId))


    reviewVal = request.POST.get('reviewVal', False)

    if not reviewVal:
        return HttpResponse(Helpers.create_json_output(Helpers.StatusCodes.InvalidRatingValue, reviewVal))

    productId = int(productId)
    
    # validate review, avoid overflow
    reviewVal = reviewVal[:1024]

    try:
        product = Product.models.Products.objects.get(id = productId)

    except Product.models.Products.DoesNotExist:
        return HttpResponse(Helpers.create_json_output(Helpers.StatusCodes.InvalidProductId, productId))


    # session is validate, safe to take userId from session
    Product.models.ProductReview.objects.create(productId = product, userId = request.session['userId'], reviewVal = reviewVal)
    

    return HttpResponse(Helpers.create_json_output(Helpers.StatusCodes.Success, ''))
Esempio n. 14
0
def reset_password(request):
    '''
        profile update
    '''

    if request.method != 'POST':
        return HttpResponse(Helpers.create_json_output(Helpers.StatusCodes.NotPostRequest, ''))

    password = request.POST.get('password', False)
    phoneNumber =  request.POST.get('phoneNumber', False)
    otpValue = request.POST.get('otpValue', False)

    # we share the otp with user as secret, only the users
    # who have correct otp and phonenumber match and valid
    # opt are allowed to add password



    # validation
    if not  otpValue or len(otpValue) != 5 or not otpValue.isdigit():
        Helpers.logger.debug('Invalid otpValue {0}'.format(otpValue))
        return HttpResponse(Helpers.create_json_output(Helpers.StatusCodes.InvalidOtpValue, otpValue))


    if not phoneNumber or len(phoneNumber) != 10 or not phoneNumber.isdigit():
        Helpers.logger.debug('Invalid phoneNumber {0}'.format(phoneNumber))
        return HttpResponse(Helpers.create_json_output(Helpers.StatusCodes.InvalidPhoneNum, phoneNumber))

    if not password or len(password) > 15 or not re.match(Settings.PASSWORD_REGEX_PATTERN, password):
        return HttpResponse(Helpers.create_json_output(Helpers.StatusCodes.InvalidPassword, ''))
    now = timezone.now()

    # validdate otp
    try:
        row = Seller.models.SellerOTPMappings.objects.get(phoneNumber=phoneNumber)
        # check if opt is correct and valid
        if row.expiaryDate > now and row.otpValue == otpValue:
            # valid otp mapping exists
            Helpers.logger.debug('Otp exists and valid {0}'.format(otpValue))
            # make the otp expired, the otp is job is done
            row.expiaryDate = now
            row.save()
            
        else:
            # already exists and valid no need to update
            Helpers.logger.debug('Otp exists, but invalid {0}'.format(otpValue))  
            return HttpResponse(Helpers.create_json_output(Helpers.StatusCodes.OtpValidationFailed, {'otpValue': otpValue }))          


    except Seller.models.SellerOTPMappings.DoesNotExist:
        # create new 
        Helpers.logger.debug('Otp doesnot exists {0}'.format(otpValue))
        return HttpResponse(Helpers.create_json_output(Helpers.StatusCodes.OtpValidationFailed, otpValue))

    appId = request.POST.get('appId', False)

    if not appId:
        return HttpResponse(Helpers.create_json_output(Helpers.StatusCodes.InvalidAppId, appId))

    # create sha512
    hashObj = hashlib.sha512()
    hashObj.update(password)
    hashObj.update(phoneNumber)
    hashObj.update(Settings.SECRET_KEY)
    hash = hashObj.hexdigest()

    try:
        row = Seller.models.Sellers.objects.get(sellerPrimaryPhone=phoneNumber)

    except Seller.models.Sellers.DoesNotExist:
        # phonenum doesn't exists, we want phonenumber to be present
        return HttpResponse(Helpers.create_json_output(Helpers.StatusCodes.InvalidPhoneNum, phoneNumber))


    # resetting password
    row.sellerPasswordHash=hash
    row.sellerAppId = appId
    row.save()

    Helpers.logger.debug('Seller password reset success with phoneNumber {0}'.format(phoneNumber))
    response = HttpResponse(Helpers.create_json_output(Helpers.StatusCodes.Success, 'reset'))   

    Helpers.create_seller_session(request, phoneNumber, row.id)

    return response
Esempio n. 15
0
def reply(request):
    if request.method != 'POST':
        return HttpResponse(Helpers.create_json_output(Helpers.StatusCodes.NotPostRequest, ''))

    if not Helpers.validate_seller_session(request):
        return HttpResponse(Helpers.create_json_output(Helpers.StatusCodes.InvalidSellerSession, ''))


    seller = request.session['sellerId']
    
    messageId = request.POST.get('messageId', False)


    if not messageId:
        return HttpResponse(Helpers.create_json_output(Helpers.StatusCodes.InvalidMessageId, {'messageId': messageId}))

    try:
        messageId = int(messageId)
    except valueError:
        return HttpResponse(Helpers.create_json_output(Helpers.StatusCodes.InvalidMessageId, {'messageId': messageId}))

    message = request.POST.get('message', False)

    if not message or not Helpers.validateMessage(message):
        return HttpResponse(Helpers.create_json_output(Helpers.StatusCodes.InvalidBargainMessage, message))
    

    toId = request.POST.get('toId', False)

    if not toId:
        return HttpResponse(Helpers.create_json_output(Helpers.StatusCodes.InvalidToid, {'messageId': toId}))

    try:
        toId = int(toId)
    except valueError:
        return HttpResponse(Helpers.create_json_output(Helpers.StatusCodes.InvalidToid, {'messageId': toId}))

    try:
        messageObj = Bargain.models.MessageBox.objects.get(id=messageId)

    except ObjectDoesNotExist:
        return HttpResponse(Helpers.create_json_output(Helpers.StatusCodes.InactiveMessage, {'messageId': messageId}))



    if messageObj.userId != toId:
        return HttpResponse(Helpers.create_json_output(Helpers.StatusCodes.InvalidToid, {'messageId': toId}))

    if not messageObj.isActive:
        return HttpResponse(Helpers.create_json_output(Helpers.StatusCodes.InactiveMessage, {'messageId': messageId}))


    

    shortMessage = Helpers.shortenMessage(message)

    # update message details
    messageObj.numOfResponses += 1
    messageObj.recentResponse = shortMessage


    messageObj.save()


    # create threads
    Bargain.models.MessageBoxThreads.objects.create(messageId = messageObj, fromId = seller.id, toId = toId, message=message)

    Bargain.models.NotificationsQueue.objects.create(appId=messageObj.userAppId, shortMessage=shortMessage)
 

    return HttpResponse(Helpers.create_json_output(Helpers.StatusCodes.Success, 'Replied!'))
Esempio n. 16
0
def delete_offerings(request):

    if request.method != 'POST':
        return HttpResponse(Helpers.create_json_output(Helpers.StatusCodes.NotPostRequest, ''))

    if not Helpers.validate_seller_session(request):
        return HttpResponse(Helpers.create_json_output(Helpers.StatusCodes.InvalidSellerSession, ''))

    categoryIdList = request.POST.get('categoryIdList', False)
    productIdList = request.POST.get('productIdList', False)
    brandIdList = request.POST.get('brandIdList', False)
    seller = request.session['sellerId']


    if not categoryIdList and not productIdList and not brandIdList:
        return HttpResponse(Helpers.create_json_output(Helpers.StatusCodes.InvalidOfferingParams, ''))

    catIdList = []
    cContents = categoryIdList.split(',')

    for c in cContents :
        try:
            catIdList.append(int(c))
        except ValueError:
            return HttpResponse(Helpers.create_json_output(Helpers.StatusCodes.InvalidCategoryIdList, categoryIdList))

    prodIdList = []
    pContents = productIdList.split(',')

    for p in pContents:
        try:
            prodIdList.append(int(p))
        except ValueError:
            return HttpResponse(Helpers.create_json_output(Helpers.StatusCodes.InvalidProductIdList, productIdList))


    branIdList = []
    bContents = brandIdList.split(',')

    for p in bContents:
        try:
            branIdList.append(int(p))
        except ValueError:
            return HttpResponse(Helpers.create_json_output(Helpers.StatusCodes.InvalidBrandIdList, brandIdList))




    for c in catIdList :
        # validate existence

        try:
            row = Product.models.CategoryTaxonomy.objects.get(id=c)
        except ObjectDoesNotExist:
            return HttpResponse(Helpers.create_json_output(Helpers.StatusCodes.InvalidCategoryIdList, c))

        # if categoryId exists, delete
        sentinel = Bargain.models.MessageRouter.objects.filter(sellerId = seller.id, productSelectionId = c, productSelectionType = Helpers.Constants.SelectionType.Category).delete()
        


    for p in prodIdList :
        try:
            row = Product.models.Products.objects.get(id=p)
        except ObjectDoesNotExist:
            return HttpResponse(Helpers.create_json_output(Helpers.StatusCodes.InvalidProductIdList, p))

        # if categoryId already exists, skip
        sentinel = Bargain.models.MessageRouter.objects.filter(sellerId = seller.id, productSelectionId = p, productSelectionType = Helpers.Constants.SelectionType.Product).delete()

    for b in branIdList:
        try:
            row = Product.models.ProductBrands.objects.get(id=b)
        except ObjectDoesNotExist:
            return HttpResponse(Helpers.create_json_output(Helpers.StatusCodes.InvalidBrandIdList, b))


        # if categoryId already exists, skip
        sentinel = Bargain.models.MessageRouter.objects.filter(sellerId = seller.id, productSelectionId = b, productSelectionType = Helpers.Constants.SelectionType.Brand).delete()
       

    return HttpResponse(Helpers.create_json_output(Helpers.StatusCodes.Success, 'Deleted!'))
Esempio n. 17
0
def signup_password(request):
    if request.method != 'POST':
        return HttpResponse(Helpers.create_json_output(Helpers.StatusCodes.NotPostRequest, ''))

    password = request.POST.get('password', False)
    phoneNumber =  request.POST.get('phoneNumber', False)
    otpValue = request.POST.get('otpValue', False)
    sellerName = request.POST.get('sellerName', False)
    cityName = request.POST.get('cityName', False)
    address = request.POST.get('address', False)
    # TODO - do we need secondary phonenumber, we need validation of 
    # secondary phonenumber before using it
    #secondaryPhone = request.POST.get('secondaryPhoneNumber', False)
    latitude = request.POST.get('latitude', False)
    longitude = request.POST.get('longitude', False)
    mailId = request.POST.get('mailId', False)
    website = request.POST.get('website', False)
    description = request.POST.get('description', False)
    appId = request.POST.get('appId', False)



    # we share the otp with user as secret, only the users
    # who have correct otp and phonenumber match and valid
    # opt are allowed to add password



    # validation
    if not  otpValue or len(otpValue) != 5 or not otpValue.isdigit():
        Helpers.logger.debug('Invalid otpValue {0}'.format(otpValue))
        return HttpResponse(Helpers.create_json_output(Helpers.StatusCodes.InvalidOtpValue, otpValue))


    if not phoneNumber or len(phoneNumber) != 10 or not phoneNumber.isdigit():
        Helpers.logger.debug('Invalid phoneNumber {0}'.format(phoneNumber))
        return HttpResponse(Helpers.create_json_output(Helpers.StatusCodes.InvalidPhoneNum, phoneNumber))

    if not password or len(password) > 15 or not re.match(Settings.PASSWORD_REGEX_PATTERN, password):
        return HttpResponse(Helpers.create_json_output(Helpers.StatusCodes.InvalidPassword, ''))
    now = timezone.now()

    # validdate otp
    try:
        otpRow = Seller.models.SellerOTPMappings.objects.get(phoneNumber=phoneNumber)
        # check if opt is correct and valid
        if otpRow.expiaryDate > now and otpRow.otpValue == otpValue:
            # rest is handled below
            pass             
            
        else:
            # already exists and valid no need to update
            Helpers.logger.debug('Otp exists, but invalid {0}'.format(otpValue))  
            return HttpResponse(Helpers.create_json_output(Helpers.StatusCodes.OtpValidationFailed, {'otpValue': otpValue }))          


    except Seller.models.SellerOTPMappings.DoesNotExist:
        # create new 
        Helpers.logger.debug('Otp doesnot exists {0}'.format(otpValue))
        return HttpResponse(Helpers.create_json_output(Helpers.StatusCodes.OtpValidationFailed, otpValue))

    # valid otp mapping exists
    Helpers.logger.debug('Otp exists and valid {0}'.format(otpValue))

    # validate other params and create seller profile if validation passes
    # keep otp alive till we validate all params

    if not sellerName or len(sellerName) > 100 or not re.match(Settings.SELLER_NAME_REGEX_PATTERN, sellerName):
        return HttpResponse(Helpers.create_json_output(Helpers.StatusCodes.InvalidSellerName, sellerName))


    if not cityName or len(cityName) > 50 or not cityName.isalpha():
        return HttpResponse(Helpers.create_json_output(Helpers.StatusCodes.InvalidCityName, cityName))


    #TODO - address validation ?
    if not address or len(address) > 300:
        return HttpResponse(Helpers.create_json_output(Helpers.StatusCodes.InvalidAddress, address))

    # http://stackoverflow.com/questions/6536232/validate-latitude-and-longitude
    if not latitude:
        return HttpResponse(Helpers.create_json_output(Helpers.StatusCodes.InvalidLatitude, latitude))
    try:
        latitude = float(latitude)
    except ValueError:
        return HttpResponse(Helpers.create_json_output(Helpers.StatusCodes.InvalidLatitude, latitude))

    if latitude < -90 or latitude > 90:
        return HttpResponse(Helpers.create_json_output(Helpers.StatusCodes.InvalidLatitude, latitude))



    if not longitude:
        return HttpResponse(Helpers.create_json_output(Helpers.StatusCodes.InvalidLongitude, longitude))
    try:
        longitude = float(longitude)
    except ValueError:
        return HttpResponse(Helpers.create_json_output(Helpers.StatusCodes.InvalidLongitude, longitude))

    if longitude < -180 or longitude > 180:
        return HttpResponse(Helpers.create_json_output(Helpers.StatusCodes.InvalidLongitude, longitude))

    # mail is optional, so validate only if provided

    if mailId:
        if not re.match(Settings.EMAIL_REGEX_PATTERN, mailId):
            return HttpResponse(Helpers.create_json_output(Helpers.StatusCodes.InvalidMailId, mailId))
    else:
        mailId = ''


    # website is optional and validate only if provided
    
    

    if website:
        urlValidator = validators.URLValidator()

        try:
            urlValidator(website)
        except ValidationError:
            return HttpResponse(Helpers.create_json_output(Helpers.StatusCodes.InvalidWebsite, website))
    else:
        website = ''
        


    # TODO - description validation ?
    # description is optional
    
    if description:
        if len(description) > 1024:
            return HttpResponse(Helpers.create_json_output(Helpers.StatusCodes.InvalidDescription, description))
    else:
        description = ''
    
     
    if not appId:
        return HttpResponse(Helpers.create_json_output(Helpers.StatusCodes.InvalidAppId, appId))






    # create sha512
    hashObj = hashlib.sha512()
    hashObj.update(password)
    hashObj.update(phoneNumber)
    hashObj.update(Settings.SECRET_KEY)
    hash = hashObj.hexdigest()
    
    row = None
    try:
        row = Seller.models.Sellers.objects.get(sellerPrimaryPhone=phoneNumber)

    except Seller.models.Sellers.DoesNotExist:
        pass



    # row already exists 
    if row:
        # phonenum already exists
        return HttpResponse(Helpers.create_json_output(Helpers.StatusCodes.PhoneNumAlreadyExists, phoneNumber))

    Helpers.logger.debug('New seller profile phone:{} name:{} city:{} ,\
            address:{} latitude:{} longitude:{} mailId:{} website:{} desc:{}'.format(\
                phoneNumber, sellerName, cityName, address, latitude, longitude, mailId, website, description))

    row = Seller.models.Sellers()

    # adding new user password 
    row.sellerPrimaryPhone = phoneNumber
    row.sellerName = sellerName
    row.sellerCityName = cityName
    row.sellerAddress = address
    row.sellerLatitude = latitude
    row.sellerLongitude = longitude
    row.sellerMailId = mailId
    row.sellerWebsite = website
    row.sellerDescription= description

    row.sellerPasswordHash=hash
    row.sellerAppId = appId

    row.save()

    Helpers.logger.debug('seller added successfully with phoneNumber {0}'.format(phoneNumber))
    response = HttpResponse(Helpers.create_json_output(Helpers.StatusCodes.Success, 'added'))   

    Helpers.create_seller_session(request, phoneNumber, row.id)

    # make the otp expired, the otp is job is done
    
    otpRow.expiaryDate = now
    otpRow.save()

    return response
Esempio n. 18
0
def product_list(request):
    
    if request.method != 'GET':
        return HttpResponse(Helpers.create_json_output(Helpers.StatusCodes.NotGetRequest, ''))
    
    if not Helpers.validate_user_session(request):
        return HttpResponse(Helpers.create_json_output(Helpers.StatusCodes.InvalidUserSession, ''))

    categoryId = request.GET.get('categoryId')

    # Validate the category ID
    if not categoryId or not categoryId.isdigit():
       return HttpResponse(Helpers.create_json_output(Helpers.StatusCodes.InvalidCategoryID, categoryId))


    startFound = request.GET.get('from')
    endFound   = request.GET.get('to')
    orderBy = ''

    # Can be extended to any kind of filtering/sorting based on Product Model attributes
    availableFilters = ['brandFilter', 'priceFilter']
    availableOrderings = ['popularity', 'reviewCount']

    # TODO : Use Q() objects to efficiently handle multiple filters and sortby.
    # for filter in availableFilters :
    #    if filter in request.GET.keys() :


    topNProducts = []
    # Check if from/to parameters are set in GET request, else return 10 popular products by default
    if not startFound and not endFound :
        try:
           topNProducts = Products.objects.filter(productCategoryId_id=categoryId)[:Settings.DEFAULT_LISTING_COUNT]
           
        except Products.DoesNotExist :
            return HttpResponse(Helpers.create_json_output(Helpers.StatusCodes.NoProductsFound, categoryId))


    if not startFound and endFound :
        try:
           end = int(endFound)
           topNProducts = Products.objects.filter(productCategoryId_id=categoryId)[:end]
           
        except Products.DoesNotExist :
            return HttpResponse(Helpers.create_json_output(Helpers.StatusCodes.NoProductsFound, categoryId))

    if startFound :
        start = int(startFound)

        if not endFound :

               try:
                   topNProducts = Products.objects.filter(productCategoryId_id=categoryId)[start : start + Settings.DEFAULT_LISTING_COUNT]
                    
               except Products.DoesNotExist:
                   return HttpResponse(Helpers.create_json_output(Helpers.StatusCodes.NoProductsFound, categoryId))
        else :
               # Both from and to are present
               end = int(endFound)

               try:
                   topNProducts = Products.objects.filter(productCategoryId_id=categoryId)[start : end]

               except Products.DoesNotExist:
                   return HttpResponse(Helpers.create_json_output(Helpers.StatusCodes.NoProductsFound, ''))
         
    
    sendNProducts = []

    for item in topNProducts :
        sendNProducts.append([item.productName, item.productMinPrice, item.productMaxPrice, item.productAvgRating] )
        
        
    return HttpResponse(Helpers.create_json_output(Helpers.StatusCodes.Success, sendNProducts))
Esempio n. 19
0
def product_reviews(request):

     # Validate if its a GET request 
     if request.method != 'GET':
        return HttpResponse(Helpers.create_json_output(Helpers.StatusCodes.NotGetRequest, ''))
    
     # Allow only if the user session is active.
     if not Helpers.validate_user_session(request):
        return HttpResponse(Helpers.create_json_output(Helpers.StatusCodes.InvalidUserSession, ''))
     
     productId = request.GET.get('productId')

     # Validate the product ID
     if not productId or not productId.isdigit():
        return HttpResponse(Helpers.create_json_output(Helpers.StatusCodes.InvalidProductId, productId))

     
     topNReviews = []
     startFound = request.GET.get('from')
     endFound   = request.GET.get('to')

      # Check if from/to parameters are set in GET request, else return 10 recent reviews by default
     if not startFound and not endFound :
         try:
            topNReviews = ProductReviews.objects.filter(productId_id=productId)[:Settings.DEFAULT_LISTING_COUNT]
            
         except ProductReviews.DoesNotExist :
             return HttpResponse(Helpers.create_json_output(Helpers.StatusCodes.NoReviewsFound, ''))
     
     if not startFound and endFound :
        try:
           end = int(endFound)
           topNProducts = ProductReviews.objects.filter(productId_id=productId)[:end]
           
        except ProductReviews.DoesNotExist :
             return HttpResponse(Helpers.create_json_output(Helpers.StatusCodes.NoReviewsFound, ''))

     sendReviews = []
     if startFound :
         start = int(startFound)

         if not endFound :

                try:
                    topNReviews = ProductReviews.objects.filter(productId_id=productId)[start : start + Settings.DEFAULT_LISTING_COUNT]
                    
                except ProductReviews.DoesNotExist:
                    return HttpResponse(Helpers.create_json_output(Helpers.StatusCodes.NoReviewsFound, ''))
         else :
               # Both from and to are present
                end = int(endFound)

                try:
                    topNReviews = ProductReviews.objects.filter(productId_id=productId)[start : end]

                except ProductReviews.DoesNotExist:
                    return HttpResponse(Helpers.create_json_output(Helpers.StatusCodes.NoReviewsFound, ''))
         
         
     for r in topNReviews :
         sendReviews.append(r.reviewVal)
        
     return HttpResponse(Helpers.create_json_output(Helpers.StatusCodes.Success, sendReviews))
Esempio n. 20
0
def send(request):

    if request.method != 'POST':
        return HttpResponse(Helpers.create_json_output(Helpers.StatusCodes.NotPostRequest, ''))
    
    if not Helpers.validate_user_session(request):
        return HttpResponse(Helpers.create_json_output(Helpers.StatusCodes.InvalidUserSession, ''))


    selectionType = request.POST.get('selectionType', False)

    if selectionType is False:
        return HttpResponse(Helpers.create_json_output(Helpers.StatusCodes.InvalidSelectionType, selectionType))

    try:
        selectionType = int(selectionType)
    except ValueError:
        return HttpResponse(Helpers.create_json_output(Helpers.StatusCodes.InvalidSelectionType, selectionType))


    
    productId = None
    brandId = None
    categoryId = None
    
    # we should get either one of these
    if selectionType == Helpers.Constants.SelectionType.Product:
        productId = request.POST.get('productId', False)
        if productId is False:
            return HttpResponse(Helpers.create_json_output(Helpers.StatusCodes.InvalidProductId, productId))

        try:
            productId = int(productId)
        except ValueError:
            return HttpResponse(Helpers.create_json_output(Helpers.StatusCodes.InvalidProductId, productId))

    elif selectionType == Helpers.Constants.SelectionType.Brand:
        brandId = request.POST.get('brandId', False)
        if brandId is False:
            return HttpResponse(Helpers.create_json_output(Helpers.StatusCodes.InvalidBrandId, brandId))

        try:
            brandId = int(brandId)
        except ValueError:
            return HttpResponse(Helpers.create_json_output(Helpers.StatusCodes.InvalidBrandId, brandId))


    elif selectionType == Helpers.Constants.SelectionType.Category:
        categoryId = request.POST.get('categoryId', False)
        if categoryId is False:
            return HttpResponse(Helpers.create_json_output(Helpers.StatusCodes.InvalidCategoryID, categoryId))

        try:
            categoryId = int(categoryId)
        except ValueError:
            return HttpResponse(Helpers.create_json_output(Helpers.StatusCodes.InvalidCategoryID, categoryId))

    else:
        return HttpResponse(Helpers.create_json_output(Helpers.StatusCodes.InvalidSelectionType, selectionType))



    if productId is None and brandId is None and categoryId is None:
        return HttpResponse(Helpers.create_json_output(Helpers.StatusCodes.InvalidSelectionType, selectionType))


    interestedInSimilar = request.POST.get('interestedInSimilar', False) != False


    latitude = request.POST.get('latitude', False)
    longitude = request.POST.get('longitude', False)


     # http://stackoverflow.com/questions/6536232/validate-latitude-and-longitude
    if not latitude:
        return HttpResponse(Helpers.create_json_output(Helpers.StatusCodes.InvalidLatitude, latitude))
    try:
        latitude = float(latitude)
    except ValueError:
        return HttpResponse(Helpers.create_json_output(Helpers.StatusCodes.InvalidLatitude, latitude))

    if latitude < -90 or latitude > 90:
        return HttpResponse(Helpers.create_json_output(Helpers.StatusCodes.InvalidLatitude, latitude))



    if not longitude:
        return HttpResponse(Helpers.create_json_output(Helpers.StatusCodes.InvalidLongitude, longitude))
    try:
        longitude = float(longitude)
    except ValueError:
        return HttpResponse(Helpers.create_json_output(Helpers.StatusCodes.InvalidLongitude, longitude))

    if longitude < -180 or longitude > 180:
        return HttpResponse(Helpers.create_json_output(Helpers.StatusCodes.InvalidLongitude, longitude))


    message = request.POST.get('message', False)
    if not message or not Helpers.validateMessage(message):
        return HttpResponse(Helpers.create_json_output(Helpers.StatusCodes.InvalidBargainMessage, message))


    # TODO - search radius
    tiles = Helpers.overlapping_tiles(latitude, longitude)

    Helpers.logger.debug('overlapping tiles {0}'.format('\t'.join(tiles)))

    # we user selected product, we will send notification to potential
    # all sellers who sells this product, this brand and this category
    # in ranking, we use whether user is interested in similar product or 
    # not to truncate

    if productId:
        row = Product.models.Products.objects.get(id=productId)
        brandId = row.brandId_id

        row = Product.models.ProductBrands.objects.get(id=brandId)
        categoryId = row.categoryId_id

    elif brandId:
        row = Product.models.ProductBrands.objects.get(id=brandId)
        categoryId = row.categoryId_id

    
    Helpers.logger.debug('productId {} brandId {} categoryId {}'.format(productId, brandId, categoryId))

    routes = []

    if productId:
        routes.extend([(t, productId, Helpers.Constants.SelectionType.Product) for t in tiles])

    if brandId:
        routes.extend([(t, brandId, Helpers.Constants.SelectionType.Brand) for t in tiles])

    if categoryId:
        routes.extend([(t, categoryId, Helpers.Constants.SelectionType.Category) for t in tiles])


    Helpers.logger.debug('Routes {}'.format('\t'.join([str(t) for t in routes])))
    sellers = []
    sellerIds = {}
    for r in routes:
        rows = Bargain.models.MessageRouter.objects.filter(tileId = r[0], productSelectionId = r[1], productSelectionType = r[2])
        for s in rows:
            if s.sellerId in sellerIds:
                continue

            sellerIds[s.sellerId] = True

            sellers.append(s)

    Helpers.logger.debug('Sellers {}'.format('\t'.join([str(s.sellerId) for i in sellers])))

    user = request.session.get('userId')

    # do some ranking
    sellers = Helpers.rankeSellers(sellers)


    # create message
    messageObj = Bargain.models.MessageBox.objects.create(userId=user.id, headMessage=message, userAppId=user.userAppId)

    
    shortMessage = Helpers.shortenMessage(message)

    for seller in sellers:
        # add message for seller

        # create threads
        Bargain.models.MessageBoxThreads.objects.create(messageId = messageObj, fromId = user.id, toId = seller.sellerId, message=message)

        Bargain.models.NotificationsQueue.objects.create(appId=seller.sellerAppId, shortMessage=shortMessage)


    return HttpResponse(Helpers.create_json_output(Helpers.StatusCodes.Success, {'numOfSeller': len(sellers)}))