def delete(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 # TODO: Check if current profile allowed to delete orders currentProfile = Profile.getProfile(request.user) if id: try: order = Order.objects.get(pk=id, user=currentProfile.parent_user) itemProduct = order.product item_id = str(order.item.id) itemProduct.delete() order.delete() updateBestPriced(None, None, item_id) return ready_data_true except ObjectDoesNotExist: ready_data_false['errors'] = "id doesn't exist, id=" + str(id) return ready_data_false else: ready_data_false['errors'] = 'id is required, id=' + str(id) return ready_data_false
def create(self, request): 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 try: item_id = request.POST.get('item_id') product_id = request.POST.get('product_id') user = request.user currentProfile = Profile.getProfile(request.user) items = request.POST.get('items') # 1. product and item are given in request, need to create Order from product if product_id: product = Product.objects.get(pk=product_id) item = Item.objects.get(pk=item_id) itemproduct = ItemProduct.objects.create( \ product_num = product.product_num, \ vendor = product.vendor, \ upc = product.upc, \ category = product.category, \ name1 = product.name1, \ name2 = product.name2, \ package = product.package, \ date_modified = product.date_modified, \ price = product.price, \ brand = product.brand, \ ispriceperunit = product.ispriceperunit, \ notes = product.notes, \ price_per_unit = 0, \ user = currentProfile.parent_user) try: Order.objects.get(item=item, product=itemproduct, user=currentProfile.parent_user) except: order = Order.objects.create(item=item, product=itemproduct, user=currentProfile.parent_user) updateBestPriced(None, None, item_id) ready_data_true['items'] = order.list() ready_data_true['total'] = 1 return ready_data_true else: # normally must be False, but this is not actual error, so it's OK return ready_data_true ready_data_false['itemproduct'] = itemproduct return ready_data_false # 2. fields are given in request to create an Order elif items: # These fields could be used to create Order # # "item_id": "1713", Order Required # "product_num": "100065", ItemProduct Required # "name1": "Foie Gras, Duck Ref Millefeuille Appetizer", ItemProduct.name1 Required # "vendor_id": "89", ItemProduct Required # "price": "", ItemProduct # "category": "", ItemProduct # "total_units_per_package": "", ItemProduct # "ispriceperunit": false, ItemProduct # "package_pack": "", ItemProduct.package # "notes": "", ItemProduct # "brand": "Food Innovations Bb", ItemProduct # "upc": "", ItemProduct # "preferred": false Order ext_posted_data = simplejson.loads(request.POST.get('items')) attrs = self.flatten_dict(ext_posted_data) data = {} ready_data_false['data'] = data if 'ispriceperunit' not in attrs: data['ispriceperunit']=False else: data['ispriceperunit']=attrs['ispriceperunit'] if 'preferred' not in attrs: preferred=False else: preferred=attrs['preferred'] data['product_num']=attrs['product_num'] data['upc']=replace(attrs['upc']) data['name1']=replace(attrs['name1']) data['name2']=replace(attrs['name2']) data['vendor_id']=attrs['vendor_id'] data['date_modified']= datetime.now() data['price'] = Decimal(str(attrs['price'])) if data['price'] == '': data['price'] = '0' data['total_units_per_package']=str(attrs['total_units_per_package']) if data['total_units_per_package'] == '': data['total_units_per_package'] = str(0) data['package']=replace(attrs['package']) data['brand']=replace(attrs['brand']) data['category']=replace(attrs['category']) data['notes']=replace(attrs['notes']) # RE: price_per_unit, update it when price or total_units_per_package or ispriceperunit are updated if not data['ispriceperunit']: if data['price'] and data['total_units_per_package'] is not '0': pricePerUnit = float(data['price'])/float(data['total_units_per_package']) p_u = str('%.3f' % (pricePerUnit,)) else: p_u = '0' else: if data['price'] and data['total_units_per_package'] is not '0': p_u = data['price'] else: p_u = '0' data['price_per_unit'] = p_u if logger.isEnabledFor(logging.DEBUG): logger.debug('data: %s' % (data)) itemproduct = ItemProduct.objects.create(user=currentProfile.parent_user, **data) item = Item.objects.get(pk=item_id) # need to avoid to have duplicate itemproducts # let's get all orders for current item # then compare orders = Order.objects.filter(item=item, user=currentProfile.parent_user) ready_data_false['orders'] = orders for order in orders: if order.product.product_num == attrs['product_num'] and order.product.vendor_id == attrs['vendor_id']: ready_data_true['items'] = order.list() return ready_data_true # there is no identical order, so let's create one order = Order.objects.create(item=item, product=itemproduct, preferred=preferred, user=currentProfile.parent_user) updateBestPriced(None, None, item_id) ready_data_true['items']=order.list() ready_data_true['total']=1 return ready_data_true return ready_data_false except Exception, err: ready_data_false['errors'] = err.message if logger.isEnabledFor(logging.ERROR): logger.error('%s' % (err)) logger.error('%s' % (traceback.format_exc())) logger.error('User: %s' % (request.user)) logger.error('Items: %s' % (items)) return ready_data_false
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
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 try: if logger.isEnabledFor(logging.DEBUG): logger.debug('request:%s' % (request)) logger.debug('request.data:%s' % (request.data)) request.method = "POST" request._load_post_and_files() request.method = "PUT" request.PUT = request.POST if logger.isEnabledFor(logging.DEBUG): logger.debug('request:%s' % (request)) logger.debug('request.data:%s' % (request.data)) logger.debug('request.PUT:%s' % (request.PUT)) items = request.PUT.get('items') if logger.isEnabledFor(logging.DEBUG): logger.debug('items:%s' % (items)) currentProfile = Profile.getProfile(request.user) parentProfile = Profile.getProfile(currentProfile.parent_user) if id: # These fields could be used to update Order # # "product_num": "100065", ItemProduct Required # "name": "Foie Gras, Duck Ref Millefeuille Appetizer", ItemProduct.name1 Required # "vendor_id": "89", ItemProduct Required # "price": "", ItemProduct # "category": "", ItemProduct # "total_units_per_package": "", ItemProduct # "ispriceperunit": false, ItemProduct # "package": "", ItemProduct.package # "notes": "", ItemProduct # "brand": "Food Innovations Bb", ItemProduct # "upc": "", ItemProduct # "order_qt": "2" Order # "on_sae": "true" Order # "preferred": false Order # "price_per_unit": "" ItemProduct ext_posted_data = simplejson.loads(items) attrs = self.flatten_dict(ext_posted_data) update_total_price = False update_best_priced = False update_price_per_unit = False if logger.isEnabledFor(logging.DEBUG): logger.debug('attrs:%s' % (attrs)) if 'vendor_id' in attrs: attrs['vendor'] = attrs['vendor_id'] del attrs['vendor_id'] order = Order.objects.select_related('item', 'product', 'product__vendor__profile').get(pk=id) # Let's find out if vendor has extra charge or discount # this value is actually stored in Relationship object relationship = Relationship.objects.get(Q(vendor=order.product.vendor.profile.id) & Q(customer=parentProfile)) ecod = relationship.ecod if 'preferred' in attrs: preferred = attrs['preferred'] del attrs['preferred'] if preferred == True: Order.objects.filter(item=order.item, preferred=True).update(preferred=False) order.preferred=preferred Order.objects.filter(item=order.item, best_priced=True).update(best_priced=False) update_best_priced = True if 'enabled' in attrs: enabled = attrs['enabled'] del attrs['enabled'] order.enabled=enabled if enabled == False: order.preferred = False # if order is disabled, it can not be prefer update_best_priced = True if 'order_qt' in attrs: order_qt = str(attrs['order_qt']) if order_qt == "None" or order_qt == "": order_qt = '0' del attrs['order_qt'] order.order_qt=order_qt update_total_price = True if 'po_notes' in attrs: po_notes = str(attrs['po_notes']) del attrs['po_notes'] order.po_notes=po_notes order.save() if 'id' in attrs: del attrs['id'] if 'date_modified' in attrs: del attrs['date_modified'] if 'total_units_per_package' in attrs: attrs['total_units_per_package'] = str(attrs['total_units_per_package']) if attrs['total_units_per_package'] == '': attrs['total_units_per_package'] = str(0) total_units_per_package = attrs['total_units_per_package'] update_total_price = True update_best_priced = True update_price_per_unit = True else: total_units_per_package = order.product.total_units_per_package if 'price' in attrs: if order.product.price is None: attrs['previous_price'] = "0" else: if int(order.product.price) is not 0: attrs['previous_price'] = order.product.price attrs['price'] = str(attrs['price']) attrs['date_modified'] = datetime.now() # change price_actual if ecod is not NONE 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'] update_total_price = True update_best_priced = True update_price_per_unit = True else: price = order.product.price if 'ispriceperunit' in attrs: ispriceperunit = attrs['ispriceperunit'] update_best_priced = True update_price_per_unit = True else: ispriceperunit = order.product.ispriceperunit # RE: price_per_unit, update it when price or total_units_per_package or ispriceperunit are updated if update_price_per_unit: if not ispriceperunit: if price and total_units_per_package is not '0': pricePerUnit = float(price)/float(total_units_per_package) p_u = str('%.3f' % (pricePerUnit,)) else: p_u = '0' else: if price and total_units_per_package is not '0': p_u = price else: p_u = '0' # change price_actual if ecod is not NONE if ecod is not None: attrs['price_per_unit'] = str( Decimal(p_u)*( (Decimal(100) + Decimal(ecod))/Decimal(100) ) ) else: attrs['price_per_unit'] = p_u itemProduct = order.product ready_data_false['itemProduct']=itemProduct itemProduct = ItemProduct.objects.filter(id=itemProduct.id).update(**attrs) if update_total_price == True: order.updateTotalPrice(); if update_best_priced == True: updateBestPriced(None, None, str(order.item.id)) ready_data_true['items'] = order.list() return ready_data_true else: ready_data_false['errors'] = u'id is required' return ready_data_false except Exception, err: ready_data_false['errors'] = err.message if logger.isEnabledFor(logging.ERROR): logger.error('%s' % (err)) logger.error('items=%s' % (err, str(request.PUT.get('items')))) return ready_data_false
def update(profile, args=None, id=None): ready_data_true = {'success': True } ready_data_false = {'success': False} try: doUpdateBestPriced = False if profile == None: raise Exception('No Profile specified') if profile.get_role_display() != 'Customer': # only Customer and Sub-customer are allowed to modify Item if profile.get_role_display() != 'Sub-customer' : logger.error("Wrong User Type: " + profile.get_role_display()) raise Exception('Not Allowed: Wrong User Type') if args == None: raise Exception('No Arguments are given') item = None item_id = None if id: item_id = id try: item = Item.objects.get(id=item_id, user=profile.parent_user) except ObjectDoesNotExist: raise Exception (u"Item is not found") if 'id' in args: item_id = args['id'] try: item = Item.objects.get(id=item_id, user=profile.parent_user) except ObjectDoesNotExist: raise Exception (u"Item is not found") if 'item_id' in args: item_id = args['item_id'] try: item = Item.objects.get(id=item_id, user=profile.parent_user) except ObjectDoesNotExist: raise Exception (u"Item is not found") if not item: raise Exception (u"Item is NOT found") if 'unit_id' in args: unit_id = args['unit_id'] try: item.unit = Unit.objects.get(id=unit_id, user=profile.parent_user) except ObjectDoesNotExist: raise Exception (u"Unit is not found") if 'category_id' in args: category_id = args['category_id'] if category_id.lower() == 'root': item.category = None else: try: item.category = Category.objects.get(id=category_id, user=profile.parent_user) except ObjectDoesNotExist: raise Exception (u"Category is not found") if 'name' in args: item.name = replace(args['name']) if 'upc' in args: upc = replace(args['upc']) if upc != '': exist = Item.objects.filter(user=profile.parent_user, upc=upc). \ exclude(id=item_id).exists() if exist == True: raise Exception ("Duplicate UPC, %s is not UNIQUE, UPDATE FAILED For UPC: %s" % (upc, item.upc)) else: item.upc = upc if 'upc_2' in args: item.upc_2 = replace(args['upc_2']) if 'upc_3' in args: item.upc_3 = replace(args['upc_3']) if 'upc_case' in args: item.upc_case = replace(args['upc_case']) if 'image_url' in args: item.image_url = replace(args['image_url']) if 'notes' in args: item.notes = replace(args['notes']) if 'inventory_no_count' in args and args['inventory_no_count'] != None: if args['inventory_no_count'] == 'false': item.inventory_no_count = False else: item.inventory_no_count = True if 'qt_in_stock' in args: qt_in_stock = args['qt_in_stock'] if qt_in_stock == '' or qt_in_stock == 'NaN': item.qt_in_stock = '0' elif float(item.qt_in_stock) != float(qt_in_stock): # change only if different item.qt_in_stock_last_updated = datetime.now() diff = float(qt_in_stock) - float(item.qt_in_stock) d = str(diff) if d.endswith('.0'): d = d[:-2] if d.endswith('.00'): d = d[:-3] if diff > 0: item.qt_in_stock_last_diff = '+' + str(d) else: item.qt_in_stock_last_diff = str(d) item.qt_in_stock = replace(qt_in_stock) if settings.HGM == True: # UPDATE qt_in_stock in WWW updateWwwQtInStock(item) if 'min_qt_in_stock' in args: min_qt_in_stock = replace(args['min_qt_in_stock']) if min_qt_in_stock == '' or min_qt_in_stock == 'NaN': min_qt_in_stock = '0' item.min_qt_in_stock = min_qt_in_stock if 'qt_to_stock' in args: qt_to_stock = replace(args['qt_to_stock']) if qt_to_stock == '' or qt_to_stock == 'NaN': qt_to_stock = '0' item.qt_to_stock = qt_to_stock if 'temp_stock' in args: temp_stock = replace(args['temp_stock']) if temp_stock == '' or temp_stock == 'NaN' or temp_stock == 'null' or temp_stock == None: item.temp_stock = None else: item.temp_stock = Decimal(temp_stock) if 'best_price' in args: best_price = replace(args['best_price']) if best_price == '' or best_price == 'NaN' or best_price == 'null' or best_price == None: item.best_price = None else: item.best_price = Decimal(best_price) if 'cost_per_unit' in args: cost_per_unit = replace(args['cost_per_unit']) if cost_per_unit == '' or cost_per_unit == 'NaN' or cost_per_unit == 'null' or cost_per_unit == None: item.cost_per_unit = None else: item.cost_per_unit = Decimal(cost_per_unit) if 'loc_stock' in args: item.loc_stock = replace(args['loc_stock']) if 'loc_ret_dept' in args: newDept = replace(args['loc_ret_dept']) if newDept == '' or newDept == 'None': logger.error('ATTEMPT TO ERAZE DEPARTMENT: upc-' + item.upc) else: item.loc_ret_dept = newDept if 'loc_ret_col' in args: item.loc_ret_col = replace(args['loc_ret_col']) if 'loc_ret_row' in args: item.loc_ret_row = replace(args['loc_ret_row']) if 'enabled' in args: if args['enabled'] == 'false': item.enabled = False else: if item.enabled != True: item.enabled = True doUpdateBestPriced = True if 'so_ignore_no_sales' in args and args['so_ignore_no_sales'] != None: if args['so_ignore_no_sales'] == 'false': item.so_ignore_no_sales = False else: item.so_ignore_no_sales = True if 'so_do_not_order' in args and args['so_do_not_order'] != None: if args['so_do_not_order'] == 'false': item.so_do_not_order = False else: item.so_do_not_order = True if 'so_always_order' in args and args['so_always_order'] != None: item.so_always_order = args['so_always_order'] if 'total_units_per_case' in args: item.total_units_per_case = replace(args['total_units_per_case']) #item.sales_price = 0 item.save() # orders from disabled items are not calculated for Best Priced # so if item is changed to enabled, need to calculate best Priced Order if doUpdateBestPriced: updateBestPriced(None, None, str(item.id)) ready_data_true['items'] = item.list(item.id) return ready_data_true except Exception, err: #if str(err).startswith( 'Duplicate UPC' ): # logger.error(err) #else: logger.error(err) raise Exception(err)