def updateDept(kwargs): file = kwargs['file'] enabled = False request = kwargs['request'] parent_user = getParentuser(request) path = "%s/%s" % (settings.UPLOAD_ITEM_DIR, file.name,) destination = open(path, 'wb+') for chunk in file.chunks(): destination.write(chunk) destination.close() csvfile = csv.reader(open(path, 'rb'), delimiter=settings.CSV_DELIMITER) #header exist -> skip header csvfile.next() i = 0 j = 0 msg = [] for row in csvfile: try: #cleaning row = clean(row) item_id = replace(str(row[0]).strip()) # remove spaces from front and back dept = replace(str(row[1]).strip()) # remove spaces from front and back if item_id == '' or dept == '': continue try: item = Item.objects.get(id=item_id) j = j+ 1 if item.loc_ret_dept != '' and item.loc_ret_dept != None and item.loc_ret_dept != " ": msg.append('loc_ret_dept=' + item.loc_ret_dept) continue else: item.loc_ret_dept = dept item.save() i = i + 1 except Exception, err: msg.append(err.message) logger.info(err.message) #something went wrong with this item, let's just continue continue except Exception, err: msg.append(err.message) logger.info(err.message) #something went wrong with this item, let's just continue continue
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 currentProfile = Profile.getProfile( request.user) try: ext_posted_data = simplejson.loads(request.POST.get('items')) attrs = self.flatten_dict(ext_posted_data) req = check(request, id=None, attrs=attrs) if req == True: reason=[] item = self.model.objects.create(\ name = replace(attrs['name']), \ category_id = attrs['category_id'], \ unit_id = attrs['unit_id'], \ upc = replace(attrs['upc']), \ upc_2 = replace(attrs['upc_2']), \ upc_3 = replace(attrs['upc_3']), \ upc_case = replace(attrs['upc_case']), \ notes=replace(attrs['notes']), \ image_url=attrs['image_url'], \ qt_in_stock=0, \ qt_to_stock=0, \ min_qt_in_stock=2, \ enabled=True, \ sales_price=0, \ loc_stock = u'',\ loc_ret_dept = u'',\ loc_ret_col = u'',\ loc_ret_row = u'',\ inventory_no_count = False,\ so_ignore_no_sales = False,\ so_do_not_order = False,\ so_always_order = 0,\ user=currentProfile.parent_user) ready_data_true['items'] = item.list(item.id) return ready_data_true else: ready_data_false['errors'] = req return ready_data_false except Exception, err: logger.error(err) logger.error('REQUEST: %s' % str(request) ) ready_data_false['errors'] = err.message ready_data_false['name'] = replace(attrs['name']) return ready_data_false
def profitReport(profile, params): ready_data_true = {'success': True } ready_data_false = {'success': False} profit = [] total = 0 try: if params == None: logger.error('No params specified') raise Exception('No params specified') # check not required param start #start = 0 #if 'start' in params: # start = int(params['start']) # check not required param limit #limit = 25 #if 'limit' in params: # limit = int(params['limit']) loc_ret_dept = None if 'loc_ret_dept' in params: loc_ret_dept = replace(params['loc_ret_dept']).strip() else: raise Exception('Location Department is Required Field') date_from = None if 'date_from' in params: date_from_index = params['date_from'].find('T') date_from = params['date_from'][0:date_from_index] date_from = date_from + " 00:00:00" else: raise Exception('Date-From is Required Field') date_to = None if 'date_to' in params: date_to_index = params['date_to'].find('T') date_to = params['date_to'][0:date_to_index] date_to = date_to + " 23:59:59" else: raise Exception('Date-To is Required Field') # For each item need to: # 2. Find total sales for date frame total_sales = 0 sales = Sales.objects.select_related('item').filter(date_from__gte=date_from, date_to__lte=date_to, \ item__loc_ret_dept=loc_ret_dept, user=profile.parent_user). \ values("item__upc", 'item__name', 'item__enabled', "item_id"). \ annotate(total_qt_sold=Sum('qt_sold'), total_sales=Sum('total_price')) return_dict = {} for sale in sales: sale['profit'] = sale['total_sales'] sale['total_expense'] = 0 return_dict[sale['item_id']] = sale in_details = InvoiceDetail.objects.select_related('item', 'invoice').filter(invoice__date__gte=date_from, invoice__date__lte=date_to, \ item__loc_ret_dept=loc_ret_dept, user=profile.parent_user). \ values("item__upc", 'item__name', "item_id"). \ annotate(total_expense=Sum('total_price')) in_count = InvoiceDetail.objects.filter(invoice__date__gte=date_from, invoice__date__lte=date_to, \ item__loc_ret_dept=loc_ret_dept, item__enabled=True, user=profile.parent_user).count() for in_detail in in_details: if in_detail['item_id'] in return_dict: return_dict[in_detail['item_id']]['total_expense'] = in_detail['total_expense'] return_dict[in_detail['item_id']]['profit'] = return_dict[in_detail['item_id']]['total_sales'] - in_detail['total_expense'] ready_data_true['items'] = return_dict.values() ready_data_true['total'] = len(return_dict) #ready_data_true['p_details'] = in_details #ready_data_true['p_count'] = in_count #ready_data_true['date_from'] = date_from #ready_data_true['date_to'] = date_to return ready_data_true # 3. Find total Expense for date frame # 4. Find total profit (Sales - Expense) # 4. Find profit % -- (profit * 100)/sales #data = {} #data['item_id'] = item.id #ata['item__name'] = item.name #data['item__upc'] = item.upc #data['sales'] = total_sales #data['expense'] = 0 #data['profit'] = 0 #data['profit_percent'] = 0 profit.append(sales) total = total + 1 ready_data_true['items'] = profit ready_data_true['total'] = total return ready_data_true except Exception, err: logger.error(err) ready_data_false['errors'] = err ready_data_false['params'] = params return ready_data_false
def createProfile(parent_user = None, params = None): if params == None: logger.error('No params specified') raise Exception('No params specified') try: # check required param company_name if 'p_company_name' not in params: raise Exception('Company Name is Required') else: company_name = replace(params['p_company_name']).strip() if company_name == '': raise Exception('Company Name is Required') if parent_user == None: """Create User""" # check not required param username if 'username' not in params: username = company_name.strip(' ') + '_' + str(random.randint(1,9999)) else: username = replace(params['username']).strip(' ') # remove all spaces, even between words if username == '': username = company_name.replace(" ", "") # remove all spaces, even between words username = username + '_' + str(random.randint(1,9999)) # check param password if 'password' not in params: password = '******' # 'password' else: password = replace(params['password']).strip() if password == None or password.strip() == '': password = '******' if User.objects.filter(username=username).exists(): raise Exception("User with User Name: '" + username + "' already Exist, Please choose another User Name") user = User.objects.create(username=username, password=password, date_joined=datetime.now()) """Create Profile""" if parent_user == None: parent_user = user else: user = parent_user # check not requried params if 'email' not in params: email = '' else: email = replace(params['email']).strip() if 'description' not in params: description = '' else: description = replace(params['description']).strip() if 'first_name' not in params: first_name = '' else: first_name = replace(params['first_name']).strip() if 'last_name' not in params: last_name = '' else: last_name = replace(params['last_name']).strip() if 'phone_num_1' not in params: phone_num_1 = '' else: phone_num_1 = replace(params['phone_num_1']).strip() if 'phone_num_2' not in params: phone_num_2 = '' else: phone_num_2 = replace(params['phone_num_2']).strip() if 'web_page' not in params: web_page = '' else: web_page = replace(params['web_page']).strip() if 'fax_num' not in params: fax_num = '' else: fax_num = replace(params['fax_num']).strip() if 'address_1' not in params: address_1 = '' else: address_1 = replace(params['address_1']).strip() if 'address_2' not in params: address_2 = '' else: address_2 = replace(params['address_2']).strip() if 'address_3' not in params: address_3 = '' else: address_3 = replace(params['address_3']).strip() if 'address_4' not in params: address_4 = '' else: address_4 = replace(params['address_4']).strip() if 'address_5' not in params: address_5 = '' else: address_5 = replace(params['address_5']).strip() if 'mobile_phone_num' not in params: mobile_phone_num = '' else: mobile_phone_num = replace(params['mobile_phone_num']).strip() if 'notes' not in params: notes = '' else: notes = replace(params['notes']).strip() if 'category' not in params: category = '' else: category = replace(params['category']).strip() # check required param role if 'role' not in params: raise Exception('role is Required') else: role = replace(params['role']).strip() if role.strip() == '': raise Exception('role is Required') # create default Settings for this profile settings = Settings.createDefaultSettings(user) newProfile = Profile( \ user = user \ ,parent_user = parent_user \ ,settings = settings \ ,role = role \ ,company_name = company_name \ ,email = email \ ,description = description \ ,first_name = first_name \ ,last_name = last_name \ ,phone_num_1 = phone_num_1 \ ,phone_num_2 = phone_num_2 \ ,web_page = web_page \ ,fax_num = fax_num \ ,address_1 = address_1 \ ,address_2 = address_2 \ ,address_3 = address_3 \ ,address_4 = address_4 \ ,address_5 = address_5 \ ,mobile_phone_num = mobile_phone_num \ ,notes = notes \ ,category = category \ ) newProfile.save() return newProfile except Exception, err: logger.error(err) raise err # throw error farther to caller
def salesReport(profile, params): ready_data_true = {'success': True } ready_data_false = {'success': False} try: if params == None: logger.error('No params specified') raise Exception('No params specified') # check not required param loc_ret_dept loc_ret_dept = None if 'loc_ret_dept' in params: loc_ret_dept = replace(params['loc_ret_dept']).strip() # check not required param num_of_weeks num_of_weeks = 4 # 4 is default if 'num_of_weeks' in params and params['num_of_weeks'] is not None: num_of_weeks = replace(params['num_of_weeks']).strip() # check not required param start start = 0 if 'start' in params: start = int(params['start']) # check not required param limit limit = 25 if 'limit' in params: limit = int(params['limit']) today = date.today() days_before = int(num_of_weeks)*7 date_to = today - timedelta(days=days_before) if loc_ret_dept != None: total = len(Sales.objects.filter(date_to__gt=date_to, user=profile.parent_user, \ item__loc_ret_dept=loc_ret_dept, item__enabled=True). \ values("upc"). \ annotate(total_qt_sold=Sum('qt_sold'), total_price=Sum('total_price'), \ cost=Sum('cost'), profit=Sum('profit'))) sales = Sales.objects.select_related('item').filter(date_to__gt=date_to, user=profile.parent_user, \ item__loc_ret_dept=loc_ret_dept, item__enabled=True). \ values("upc", 'item__name', "item_id", 'item__qt_in_stock', 'item__loc_ret_dept', \ 'item__loc_ret_col', 'item__min_qt_in_stock', 'item__notes'). \ annotate(total_qt_sold=Sum('qt_sold'), total_price=Sum('total_price'), \ cost=Sum('cost'), profit=Sum('profit'))[start:start+limit] else: total = len(Sales.objects.filter(date_to__gt=date_to, user=profile.parent_user, item__enabled=True). \ values("upc"). \ annotate(total_qt_sold=Sum('qt_sold'), total_price=Sum('total_price'), \ cost=Sum('cost'), profit=Sum('profit'))) sales = Sales.objects.filter(date_to__gt=date_to, user=profile.user, item__enabled=True). \ values("upc", 'item__name', "item_id", 'item__qt_in_stock', 'item__loc_ret_dept', \ 'item__loc_ret_col', 'item__min_qt_in_stock', 'item__notes'). \ annotate(total_qt_sold=Sum('qt_sold'), total_price=Sum('total_price'), \ cost=Sum('cost'), profit=Sum('profit'))[start:start+limit] #data = {} #data['total_qt_sold'] =sales[0].total_qt_sold #data['description'] =sales[0].description #data['total_price'] =sales[0].total_price #data['upc'] =sales[0].upc #ready_data_true['items'] = data ready_data_true['items'] = sales #ready_data_true['sales-0'] = sales[0] ready_data_true['total'] = total ready_data_true['days_before'] = str(days_before) ready_data_true['date_to'] = str(date_to) ready_data_true['num_of_weeks'] = num_of_weeks return ready_data_true except Exception, err: logger.error(err) ready_data_false['errors'] = err 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)
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["errors"] = "Authorization is failed" return ready_data_false #if 'item_id' in request.GET: # item_id = int(request.GET.get('item_id')) hgm = settings.HGM if hgm != True: ready_data_false["error"] = "Not HGM" return ready_data_false try: currentProfile = Profile.getProfile(request.user) hgm_www_host = settings.HGM_WWW_HOST hgm_www_port = settings.HGM_WWW_PORT hgm_www_user = settings.HGM_WWW_USER hgm_www_password = settings.HGM_WWW_PASSWORD hgm_www_db = settings.HGM_WWW_DB # CONNECTION TO www.hudsongreenemarket.com 52.0.0.79 myDB = MySQLdb.connect(host=hgm_www_host,port=hgm_www_port,user=hgm_www_user,passwd=hgm_www_password,db=hgm_www_db) cHandler = myDB.cursor() #filter_by_day filter_by_day = request.GET.get('filter_by_day') #logger.debug(filter_by_day) if filter_by_day == None: filter_by_day = 'today' today = date.today() #logger.info('today: %s' % today) if filter_by_day == '3_days': from_the_date = today - timedelta(days=3) date_from = date.strftime(from_the_date, "%Y-%m-%d") # in sql will count from am elif filter_by_day == '7_days': from_the_date = today - timedelta(days=7) date_from = date.strftime(from_the_date, "%Y-%m-%d") # in sql will count from am elif filter_by_day == '14_days': from_the_date = today - timedelta(days=14) date_from = date.strftime(from_the_date, "%Y-%m-%d") # in sql will count from am elif filter_by_day == '30_days': from_the_date = today - timedelta(days=30) date_from = date.strftime(from_the_date, "%Y-%m-%d") # in sql will count from am else: date_from = date.strftime(today, "%Y-%m-%d") # in sql will count from am date_from = date_from + " 03:59:59" # off 4 hours, New York Time status_clause = '' filter_by_status = request.GET.get('filter_by_status') if filter_by_status is None: status_clause = "AND orders.order_status='U' " # Confirmed By Shopper if filter_by_status is not None and filter_by_status != 'status_all': status_clause = "AND orders.order_status='" + filter_by_status + "' " sql = "SELECT orders.virtuemart_order_id, orders.virtuemart_user_id, orders.order_number, " + \ "orders.customer_number, orders.order_total, orders.order_SalesPrice, " + \ "orders.order_Subtotal, orders.order_Tax, orders.order_shipment, " + \ "orders.order_payment, orders.order_status, orders.ip_address, orders.created_on, " + \ "customer.first_name, customer.last_name, customer.phone_1, " + \ "customer.email, customer.company, customer.address_1, " + \ "customer.address_2, customer.city, state.state_name, customer.zip, customer.customer_note, " + \ "shipment.shipment_name " + \ "from emk8r_virtuemart_orders AS orders " + \ "LEFT JOIN emk8r_virtuemart_order_userinfos AS customer " + \ "ON orders.virtuemart_order_id=customer.virtuemart_order_id "+ \ "LEFT JOIN emk8r_virtuemart_states AS state " + \ "ON customer.virtuemart_state_id=state.virtuemart_state_id "+ \ "LEFT JOIN emk8r_virtuemart_shipmentmethods_en_gb AS shipment " + \ "ON orders.virtuemart_shipmentmethod_id=shipment.virtuemart_shipmentmethod_id "+ \ "WHERE orders.created_on > '" + date_from + "' " + \ status_clause + \ "ORDER BY orders.created_on ASC " #logger.info(sql) cHandler.execute(sql) results = cHandler.fetchall() orders_len = len(results) ready_data_true['total'] = orders_len all_data = [] if orders_len == 0: #ready_data_true['items'] = {} return ready_data_true status_options = {'P' : 'Pending', 'U' : 'Confirmed By Shopper', 'C' : 'Confirmed By HGM', \ 'X' : 'Canceled', 'R' : 'Refunded', 'S' : 'Shipped', 'O' : 'Out Of Stock',} for result in results: try: data = {} data['id'] = result[0] data['virtuemart_order_id'] = result[0] data['virtuemart_user_id'] = result[1] data['order_number'] = result[2] data['customer_number'] = result[3] data['order_total'] = result[4] data['order_SalesPrice'] = result[5] data['order_Subtotal'] = result[6] data['order_Tax'] = result[7] data['order_shipment'] = result[8] data['order_payment'] = result[9] data['order_status'] = status_options[result[10]] data['ip_address'] = result[11] order_date_time = timestring.Date(result[12]) order_date_time = order_date_time - '4 hour' data['created_on'] = str(order_date_time) data['first_name'] = replace(result[13]) data['last_name'] = replace(result[14]) data['phone_1'] = result[15] data['email'] = result[16] data['company'] = replace(result[17]) data['address_1'] = replace(result[18]) data['address_2'] = replace(result[19]) data['city'] = result[20] data['state'] = result[21] data['zip'] = result[22] data['customer_note'] = result[23] data['shipment_name'] = result[24] try: sql = "SELECT SUM(product_quantity), SUM(packed_qt) FROM emk8r_virtuemart_order_items " + \ "WHERE emk8r_virtuemart_order_items.virtuemart_order_id = '" + str(data['virtuemart_order_id']) + "'; " cHandler.execute(sql) results = cHandler.fetchone() data['total_product_qt'] = int(results[0]) data['total_packed_product_qt'] = int(results[1]) except Exception, err: logger.error(err) all_data.append(data) except Exception, err: logger.error(err)
def shrinkageReport(profile, params): ready_data_true = {"success": True} ready_data_false = {"success": False} shrinkage = {} total = 0 try: if params == None: logger.error("No params specified") raise Exception("No params specified") # check not required param start start = 0 if "start" in params: start = int(params["start"]) # check not required param limit limit = 25 if "limit" in params: limit = int(params["limit"]) # param item_id item_id = None if "item_id" in params: item_id = replace(params["item_id"]).strip() if item_id != "": shrinkage = ( Inventory_Shrinkage.objects.filter(item=item_id, user=profile.parent_user) .values( "item__upc", "item__name", "item_id", "item__qt_in_stock", "item__loc_ret_dept", "item__loc_ret_col", "item__min_qt_in_stock", "item__notes", "reason", "date_time", "qt", "total_price", ) .order_by("-date_time")[start : start + limit] ) total = Inventory_Shrinkage.objects.filter(item=item_id, user=profile.parent_user).count() else: # param loc_ret_dept loc_ret_dept = None if "loc_ret_dept" in params: loc_ret_dept = replace(params["loc_ret_dept"]).strip() # param date_from date_from = None if "date_from" in params: date_from = params["date_from"] # param date_to date_to = None if "date_to" in params: date_to = params["date_to"] if loc_ret_dept != None and loc_ret_dept != "": total = len( Inventory_Shrinkage.objects.select_related("item") .filter( date_time__gt=date_from, date_time__lt=date_to, user=profile.parent_user, item__loc_ret_dept=loc_ret_dept, item__enabled=True, ) .values("item__upc") .annotate(qt=Sum("qt"), total_price=Sum("total_price")) ) shrinkage = ( Inventory_Shrinkage.objects.select_related("item") .filter( date_time__gt=date_from, date_time__lt=date_to, user=profile.parent_user, item__loc_ret_dept=loc_ret_dept, item__enabled=True, ) .values( "item__upc", "item__name", "item_id", "item__qt_in_stock", "item__loc_ret_dept", "item__loc_ret_col", "item__min_qt_in_stock", "item__notes", "reason", ) .annotate(qt=Sum("qt"), total_price=Sum("total_price")) .order_by("item__name")[start : start + limit] ) elif date_from != None and date_from != "": total = len( Inventory_Shrinkage.objects.select_related("item").filter( date_time__gt=date_from, date_time__lt=date_to ) ) # , \ # user=profile.parent_user, item__enabled=True). \ # values("item__upc"). \ # annotate(qt=Sum('qt'), total_price=Sum('total_price'))) shrinkage = ( Inventory_Shrinkage.objects.select_related("item") .filter( date_time__gt=date_from, date_time__lt=date_to, user=profile.parent_user, item__enabled=True ) .values( "item__upc", "item__name", "item_id", "item__qt_in_stock", "item__loc_ret_dept", "item__loc_ret_col", "item__min_qt_in_stock", "item__notes", "reason", ) .annotate(qt=Sum("qt"), total_price=Sum("total_price")) .order_by("item__name")[start : start + limit] ) ready_data_true["items"] = shrinkage ready_data_true["total"] = total return ready_data_true except Exception, err: logger.error(err) ready_data_false["errors"] = err return ready_data_false
def worker(req): vendor = req.params()['vendor'] user = req.params()['user'] parent_user_id = req.params()['parent_user_id'] #with transaction.commit_on_success(): orders = Order.objects.select_related().filter(product__vendor=vendor, order_qt__gt=0, user=parent_user_id) if len(orders) > 0: #create new PO purchase = Purchase.objects.create(date=datetime.now(), vendor=vendor, user_id=parent_user_id) for order in orders: if order.product.total_units_per_package is None: order.product.total_units_per_package = 0 if order.product.price is None: order.product.price = 0 if order.item.sales_price is None: order.item.sales_price = 0 total_price = 0 #add products into PO PurchaseDetail.objects.create( \ date_modified = order.product.date_modified, \ best_priced = order.best_priced, \ item = order.item, \ ispriceperunit = order.product.ispriceperunit, \ mismatch = False, \ notes = replace(order.po_notes), \ order_qt = order.order_qt, \ received_qt = 0, \ outofstock = False, \ sales_price = order.item.sales_price, \ price = order.product.price, \ product = order.product, \ purchase = purchase, \ so_notes = order.product.so_notes, \ total_price = order.total_price, \ #total_units = order.product.total_units_per_package*order.order_qt, \ total_units = 0, \ total_units_per_package = order.product.total_units_per_package, \ user_id = parent_user_id, \ inventory_updated = 1, \ verified = False) #blank order order.order_qt = None order.order_qt_so = None order.total_price = None order.po_notes = '' order.save() #archiving ?? not sure what it does, Vito(8/25/12) #order.product.use = True #vendor.use = True #order.product.save() #vendor.save() numberUpdated = ItemProduct.objects.filter(vendor=vendor, user=parent_user_id).update(so_notes='') return { "success": True, "message": "Purchase has been created", "items": purchase.list(), 'so_updated': str(numberUpdated),\ "purchase_id": str(purchase.id)} else: return { "success": False, "errors": "Purchase can't been created. You dont't have any order." }
def handle_uploaded_file(kwargs): file = kwargs['file'] category_id = kwargs['category_id'] enabled = kwargs['enabled'] deleteItems = kwargs['deleteItems'] request = kwargs['request'] parent_user = getParentuser(request) if enabled == "true" or enabled == "on": enabled = True else: enabled = False if deleteItems == "true": deleteItems = True else: deleteItems = False category = Category.objects.get(id=category_id, user=parent_user) path = "%s/%s" % (settings.UPLOAD_ITEM_DIR, file.name,) destination = open(path, 'wb+') for chunk in file.chunks(): destination.write(chunk) destination.close() csvfile = csv.reader(open(path, 'rb'), delimiter=settings.CSV_DELIMITER) #header exist -> skip header csvfile.next() i = 0 j = 0 units, u_created = Unit.objects.get_or_create(name='Ea', user=parent_user) unit_id = units.id msg = [] #time_delay_at = 50 #delay_count = 0 for row in csvfile: try: #delay_count = delay_count + 1 #if time_delay_at == delay_count: # time.sleep(1) # Delay for 1 seconds, due to slow server # time_delay_at = time_delay_at + 50 #cleaning row = clean(row) name = replace(str(row[0]).strip()) # remove spaces from front and back try: # check if there is optional location department upc = replace(str(row[1]).strip()) # remove spaces from front and back except Exception, err: #msg.append(err.message) upc = '' loc_ret_dept = '' try: # check if there is optional location departmen loc_ret_dept = replace(str(row[2]).strip()) # remove spaces from front and back except Exception, err: #msg.append(err.message) loc_ret_dept = '' if loc_ret_dept == None or loc_ret_dept == 'None': loc_ret_dept = '' if upc == None or upc == 'None': upc = '' if name == '' or upc == '': i = i+1 msg.append('name='+ name + ', upc=' + upc) continue if deleteItems == True: Item.objects.filter(upc=upc, user =parent_user).delete() continue obj, created = Item.objects.get_or_create(upc=upc, user =parent_user, defaults={ 'name': name, 'category_id': category_id, 'unit_id': unit_id, 'upc_2': u'', 'upc_3': u'', 'upc_case': u'', 'notes': u'', 'image_url': u'', 'qt_in_stock': 0, 'qt_to_stock': 0, 'min_qt_in_stock': 2, 'enabled': enabled, 'sales_price': 0, 'loc_stock': u'', 'loc_ret_dept': loc_ret_dept, 'loc_ret_col': u'', 'loc_ret_row': u'', 'inventory_no_count': False, 'so_ignore_no_sales': False, 'so_do_not_order': False, 'so_always_order': 0 }) if not created: i = i+1 msg.append('already exist: upc=' + upc) #if loc_ret_dept != '': # obj.loc_ret_dept = loc_ret_dept if obj.enabled == True: obj.save() continue # to avoid error of disableing good items if obj.enabled != enabled: # check if enabled is different and change it if it is obj.enabled = enabled obj.save() j = j+1