Esempio n. 1
0
    def read(self, request, id=None):
        
        ready_data_true =  {'success': True }
        ready_data_false = {'success': False}

        if not request.user.is_authenticated():
            ready_data_false["error"] = "Authorization is failed"
            return ready_data_false

        start    = request.GET['start']
        limit    = request.GET['limit']

        sort = []
        if 'sort' in request.GET :

            sortArr = simplejson.loads(request.GET.get('sort'))

            for s in sortArr:
                if s['direction'] == 'DESC':
                    s['property'] = '-' + s['property']
                    sort.append(s['property'])
                else:  # 'ASC'
                    s['property'] = s['property']
                    sort.append(s['property'])

        if 'customer' in request.GET:  # user is Vendor or VS they put customer id in request
                try:
                    customer = request.GET['customer']
                    customer_id = Profile.objects.get(pk=customer).user_id   # id in auth_user
                except:
                    ready_data_false['errors'] = u'Customer id is wrong'
                    return ready_data_false
        else:
            ready_data_false['msg'] = u'Customer id is required' # means user is not VS or Vendor
            ready_data_false

        if id:
            req=check(id=id, request=request)
            req.worker()
            if req.success:
                ready_data_true['items'] = req.data['itemproduct']
                ready_data_true['total'] = 1
                return ready_data_true
            else:
                ready_data_false['errors'] = req.reason
                return ready_data_false
        else:  # no id, return all products
            req=check(id=id, request=request)
            req.worker()
            if req.success:
                userProfile = req.profile
                vendor_id = Vendor.objects.get(user=userProfile.parent_user_id).id

                if 'filter' in request.GET:
                    filter   = request.GET['filter']
                    total = ItemProduct.objects.filter(user=customer_id, vendor=vendor_id, name1__icontains=filter).count()
                    products = ItemProduct.objects.filter(user=customer_id, vendor=vendor_id, name1__icontains=filter).extra(order_by = sort)[start:int(start)+int(limit)]
                    if total == 0:  #if search did not find a filter let's also look in field product_num
                        ready_data_true['items'] = ItemProduct.objects.filter(user=customer_id, vendor=vendor_id, product_num__icontains=filter)[start:int(start)+int(limit)]
                        ready_data_true['total'] = len(ItemProduct.objects.filter(user=customer_id, vendor=vendor_id, product_num__icontains=filter))
                    else:
                        ready_data_true['items'] = products
                        ready_data_true['total'] = len(ItemProduct.objects.filter(user=customer_id, vendor=vendor_id, name1__icontains=filter))
                else:
                    ready_data_true['items'] = ItemProduct.objects.filter(user=customer_id, vendor=vendor_id).extra(order_by = sort)[start:int(start)+int(limit)]
                    ready_data_true['total'] = len(ItemProduct.objects.filter(user=customer_id, vendor=vendor_id))

                    

                return ready_data_true
            else:
                return req.reason
Esempio n. 2
0
    def update(self, request, id=None):

        ready_data_true =  {'success': True }
        ready_data_false = {'success': False}

        if not request.user.is_authenticated():
            ready_data_false["error"] = "Authorization is failed"
            return ready_data_false

            
        itemproduct = ''
        itemIds = None
        updateBestPricedCount = 0

        if 'items' in request.PUT:
            if id:    # this should be situation when a single item is being updated
                ext_posted_data = simplejson.loads(request.POST.get('items'))
                attrs = self.flatten_dict(ext_posted_data)

                req=check(id=id, request=request, attrs=attrs)
                
                req.worker()
                if req.success and req.role == 'Vendor':
                    itemproduct = req.data['itemproduct']
                    itemproduct.date_modified = datetime.now()
                    if itemproduct.price is not 0:
                        itemproduct.previous_price=itemproduct.price
                    itemproduct.price = req.attrs['price']
                    itemproduct.save()
                    itemIds = Order.objects.filter(product=itemproduct).values_list('item')
                    #  there are item products in db that we don't delete, but has no reference to Item
                    #  in that situation need to just continue, we updated item product that is not being used
                    if len(itemIds) > 0:
                        updateBestPriced(None, None, str(itemIds[0][0]))                                                            
                    ready_data_true['items'] = itemproduct
                    ready_data_true['total'] = 1
                    return ready_data_true
                if req.success and req.role == 'Vendor salesmen':
                    itemproduct = req.data['itemproduct']
                    itemproduct.date_modified = datetime.now()
                    itemproduct.previous_price = itemproduct.price
                    itemproduct.price = req.attrs['price']
                    itemproduct.save()
                    itemIds = Order.objects.filter(product=itemproduct).values_list('item')

                    #  there are item products in db that we don't delete, but has no reference to Item
                    #  in that situation need to just continue, we updated item product that is not being used
                    if len(itemIds) > 0:
                        updateBestPriced(None, None, str(itemIds[0][0]))
                    else:
                        ready_data_true['attrs'] = attrs
                        ready_data_true['customer_list'] = req.customer_list

                    ready_data_true['items'] = itemproduct
                    ready_data_true['total'] = 1
                    return ready_data_true
                elif req.success and req.role == 'Customer':
                    itemproduct = ItemProduct.objects.filter(pk=id).update(date_modified=datetime.now()**attrs)
                else:
                    ready_data_false['errors'] = req.reason
                    return ready_data_false

            else:  # this is situation when multiple data is loaded, from csv
                #logger.info('Inside Else Statement')

                ext_posted_data = simplejson.loads(request.POST.get('items'))
                #ready_data_true['count'] = len(ext_posted_data)
                #return ready_data_true
                
                user_customer_id = 0
                vendor_id = 0

                # user is Vendor or Vs
                if 'customer' in request.GET:
                    customer = request.GET['customer']
                    profile = Profile.getProfile(request.user)
                    user_customer_id=profile.user.id
                    user_vendor = profile.parent_user
#                    return str(user_vendor)
                    vendor_id = Vendor.objects.get(user=user_vendor).id

                # user is customer
                elif 'vendor' in request.GET:
                    vendor_id = request.GET['vendor']
                    profile = Profile.getProfile(request.user)
                    user_customer_id=profile.parent_user.id
                    parentProfile = Profile.getProfile(profile.parent_user)

                    # Let's find out if vendor has extra charge or discount
                    # this value is actually stored in Relationship object
                    vendor = Vendor.objects.select_related('profile').get(id=vendor_id)
                    relationship = Relationship.objects.get(Q(vendor=vendor.profile.id) & Q(customer=parentProfile))
                    ecod = relationship.ecod # extra charge or discount

                else:
                    ready_data_false['errors'] = u'Customer ID or Vendor Id is required'
                    return ready_data_false

                on_sale = False
                if 'mark_all_on_sale' in request.GET:
                    on_sale_value = request.GET['mark_all_on_sale']
                    if on_sale_value == 'true':
                        on_sale = True


                count = 0
                #logger.info('Update Prices before loop')
                for attrs in ext_posted_data:
                    try:
                        #logger.info('---------------------Looping ext_posted_data---------------------')
                        price = 0
                        if 'price' in attrs:
                            if attrs['price'] == '':
                                attrs['price'] = '0'
                            attrs['price'] = Decimal(str(attrs['price']).replace(',','.').replace('$','').replace(' ', ''))
                            if ecod is not None:
                                attrs['price_actual'] = str( Decimal(attrs['price'])*(  (Decimal(100) + Decimal(ecod))/Decimal(100) ) )
                            else:
                                attrs['price_actual'] = attrs['price']

                            price=attrs['price_actual']
                            #logger.info("price:%s" % price)

                        else: pass

                        if 'product_num' in attrs:
                            if attrs['product_num'] == '': pass
                            if attrs['product_num'] == '0': pass

                            #attrs['product_num'] = attrs['product_num'].strip().lstrip('0') # remove leading 0 and spaces
                            attrs['product_num'] = attrs['product_num'].strip() # remove spaces
                            #attrs['product_num'] = re.sub("^0+","",attrs['product_num'])    # remove all leading 0
                        else: pass

                        if 'uos' in attrs: # Unit Of Sale
                            attrs['uos'] = attrs['uos'].strip() # remove spaces

                        #logger.info('prod_num=' + attrs['product_num'] + ', user_id=' + str(user_customer_id) + ', vendor_id=' + str(vendor_id))
                        #orders = Order.objects.select_related('product', 'item').filter(product__product_num__iendswith=attrs['product_num'], \
                        orders = Order.objects.select_related().filter(product__product_num=attrs['product_num'], \
                                user=user_customer_id, product__vendor=vendor_id)

                        for order in orders:
                            #logger.info('Looping order.product.product_num=' + str(order.product.product_num) + ', order_id=' + str(order.id))
                            #if re.sub("^0+","",order.product.product_num) != attrs['product_num']:
                            #    continue # skip if product numbers are not the same

                            if 'uos' in attrs:
                                if attrs['uos'] and attrs['uos'] != '':
                                    order.product.total_units_per_package = attrs['uos'] # update total_units_per_package before calculations

                            # CALCULATE price_per_unit
                            if not order.product.ispriceperunit:
                                if order.product.total_units_per_package and price:
                                    pricePerUnit = float(price)/float(order.product.total_units_per_package)
                                    attrs['price_per_unit']      = str('%.3f' % (pricePerUnit,))
                                else:
                                    attrs['price_per_unit']      = '0'
                            else:

                                if order.product.total_units_per_package and price:

                                    attrs['price_per_unit']      = price
                                else:
                                    attrs['price_per_unit']      = '0'

                            best_price_per_unit = order.item.best_price
                            is_best_priced = order.best_priced

                            order.product.date_modified=datetime.now()
                            if order.product.price is None:
                                order.product.price = 0
                            if int(order.product.price) is not 0:
                                order.product.previous_price=order.product.price
                            order.product.price=attrs['price']
                            order.product.price_actual=attrs['price_actual']
                            order.product.price_per_unit=attrs['price_per_unit']
                            order.product.on_sale = on_sale
                            order.product.save()

                            doUpdateBestPriced = False
                            if order.enabled == True and order.item.enabled == True:
                                if is_best_priced: # this order was best priced
                                    if order.preferred: # this order is preferred so need to recalculate best price
                                        order.item.best_price = order.product.price_per_unit
                                        order.item.save() # calls DB
                                    else: # not preferred
                                        if float(order.product.price_per_unit) == 0 or float(order.product.price_per_unit) > float(best_price_per_unit):  # new price is more than old price
                                            doUpdateBestPriced = True
                                        else:
                                            order.item.best_price = order.product.price_per_unit
                                            order.item.save() # calls DB
                                else: # this order was not best priced
                                    # see if there is other preferred order for the item
                                    if Order.objects.filter(item=order.item, preferred=True).exists():
                                        pass # no need to update Best Price, Best price belongs to preferred order
                                    else:
                                        # new price is less then best price
                                        if float(order.product.price_per_unit) > 0 and float(order.product.price_per_unit) < float(best_price_per_unit):
                                            Order.objects.filter(item=order.item).update(best_priced=False)# calls DB
                                            order.best_priced = True
                                            order.save() # calls DB
                                            order.item.best_price = order.product.price_per_unit
                                            order.item.save() # calls DB
                                        else:
                                            doUpdateBestPriced = True

                            #logger.info('doUpdateBestPriced: %s' % doUpdateBestPriced)
                            if doUpdateBestPriced:
                                updateBestPriced(None, None, str(order.item.id))
                                updateBestPricedCount = updateBestPricedCount + 1

                            count += 1

                    except Exception, err:
                        #ready_data_true['itemIds'] = itemIds
                        ready_data_true[attrs['product_num']] = err
                        #ready_data_true[attrs['product_num'] + ' order.product'] = order.product
                        continue

                logger.debug('Update Prices after loop')
                ready_data_true['total'] = count
                ready_data_true['updateBestPricedCount'] = updateBestPricedCount
                return ready_data_true