def smart_status_choice(cls, work_order, somax_status, due_days, create_date): task_obj = Tasks.objects.filter(work_order=work_order) if task_obj.exists(): current_status = task_obj[0].current_status # create_date = task_obj[0].create_date if due_days: today = UDatetime.now_local() is_overdue = ((create_date + due_days) < today) if is_overdue: if current_status in cls.open_status and somax_status in cls.open_status: if current_status == 'Scheduled' or somax_status == 'Scheduled': current_status = 'Complete' else: current_status = 'Canceled' elif current_status in cls.close_status and somax_status in cls.open_status: current_status = current_status else: current_status = somax_status else: if current_status in cls.open_status and somax_status in cls.open_status: if somax_status == 'Scheduled' and current_status != 'Scheduled': current_status = 'Approved' elif somax_status == 'Approved' and current_status == 'Work Request': current_status = 'Approved' else: current_status = current_status elif current_status in cls.close_status and somax_status in cls.open_status: current_status = current_status else: current_status = somax_status else: if current_status in cls.open_status and somax_status in cls.open_status: current_status = current_status elif current_status in cls.close_status and somax_status in cls.open_status: current_status = current_status else: current_status = somax_status else: current_status = somax_status if due_days: today = UDatetime.now_local() is_overdue = ((create_date + due_days) < today) if is_overdue: if somax_status in ['Approved', 'Work Request']: current_status = 'Canceled' elif somax_status in ['Scheduled']: current_status = 'Complete' else: if somax_status == 'Scheduled': current_status = 'Approved' else: if somax_status == 'Scheduled': current_status = 'Approved' return current_status
def food_price_load_processor(cls): file_path_food = os.path.join( BASE_DIR, 'RM/Centers/sample/config/master food.xlsx') food_records = pd.read_excel(file_path_food) centers = Centers.objects.all() for center in centers: menu = center.food_menu if menu: food_tier = center.food_tier food_kiosk = center.food_kiosk food_tier = 'tier ' + food_tier if food_kiosk: food_tier = 'kiosk ' + food_tier food_record = food_records[food_records['Menu'] == menu] menu = Menu.objects.get(name=center.food_menu) effective_datetime = UDatetime.now_local() for index, row in food_record.iterrows(): food = Food.objects.get(name=row['Product Description']) price = round(float(row[food_tier]), 2) RetailFoodPrice.objects.update_or_create( center_id=center, food=food, menu=menu, defaults={ 'price': price, 'status': 'active', 'effective_datetime': effective_datetime })
def create(request, *args, **kwargs): page_size = request.GET.get('limit') offset = request.GET.get('offset') filters = request.GET.get('filter') sort = request.GET.get('sort') order = request.GET.get('order') product = request.GET.get('product') as_of_date = request.GET.get('as_of_date') try: as_of_date = UDatetime.datetime_str_init(as_of_date).date() except Exception as e: as_of_date = UDatetime.now_local().date() pagination = True if page_size: page_size = int(page_size) if offset: offset = int(offset) if product == 'event bowling': product_ids = ProductChoice.event_bowling_product_ids elif product == 'event shoe': product_ids = ProductChoice.event_shoe_product_ids elif product == 'event basic packages': product_ids = ProductChoice.event_basic_packages_product_ids else: product_ids = ProductChoice.event_bowling_product_ids response = DataDAO.get_centers(pagination=pagination, page_size=page_size, offset=offset, filters=filters, sort=sort, order=order, last_price=True, last_price_product_ids=product_ids, last_price_from_change=True, as_of_date=as_of_date, opt=False) # print(response) data = response[0] num = response[1] if pagination: if not data.empty: data = data.where((pd.notnull(data)), '-') data_response = data.to_dict(orient='records') response = {'total': num, 'rows': data_response} else: response = {'total': 0, 'rows': []} else: if not data.empty: data = data.where((pd.notnull(data)), '-') response = data.to_dict(orient='records') else: response = {'total': 0, 'rows': []} return JsonResponse(response, safe=False)
def bulk_price_change_task(start, end, product, DOW, price, centers, user, tracking_id): start = UDatetime.datetime_str_init(start) start_report = start if not end: end = max(UDatetime.now_local() + datetime.timedelta(days=13), start + datetime.timedelta(days=13)) end_report = None else: end = UDatetime.datetime_str_init(end) end_report = end start = start.date() end = end.date() user = User.objects.get(username=user) tracking_id = Tracking.objects.get(tracking_id=tracking_id) DataReviseDAO.pricing_new3(start, end, product, DOW, price, centers, user, start_report, end_report, tracking_id=tracking_id) return
def create(request, *args, **kwargs): page_size = int(request.GET.get('limit')) offset = int(request.GET.get('offset')) filters = request.GET.get('filter') sort = request.GET.get('sort') order = request.GET.get('order') start = request.GET.get('start') end = request.GET.get('end') menu_id = request.GET.get('menu_id') # Get all selection values (used specifically in Center selection) category = request.GET.getlist('category') district = request.GET.getlist('district') region = request.GET.getlist('region') center_id = request.GET.getlist('center_id') # Find if all in the selections if category and 'all' in category: category = [] if district and 'all' in district: district = [] if region and 'all' in region: region = [] if center_id and 'all' in center_id: center_id = [] # Remove empty string category = [item for item in category if item] district = [item for item in district if item] region = [item for item in region if item] center_id = [item for item in center_id if item] start = UDatetime.datetime_str_init( start).date() if start else UDatetime.now_local().date() data, num = FoodDataDao.getFoodByCenter( menu_id, start, category, district, region, center_id, pagination=True, page_size=page_size, offset=offset, filters=filters, sort=sort, order=order, ) if not data.empty: data = data.where((pd.notnull(data)), "-") data_response = data.to_dict(orient='records') response = {'total': num, 'rows': data_response} else: response = {'total': 0, 'rows': []} return JsonResponse(response, safe=False)
def edit(request, *args, **kwargs): current_user = request.user product_id = request.GET.get('product_id') menu_id = request.GET.get('menu_id') category = request.GET.get('category') field = request.GET.get('field') new_value = request.GET.get(field) old_value = request.GET.get('old_value') start = request.GET.get('start') end = request.GET.get('end') center_id = field start = UDatetime.datetime_str_init( start).date() if start else UDatetime.now_local().date() end = UDatetime.datetime_str_init(end).date() if end else None price = { 'price_symbol': 'equal', 'price': float(new_value), 'unit': 'dollar' } category_products = [(category, product_id)] centers = [center_id] # Get Menu menu = Menu.objects.filter( menu_id=menu_id ) #get (as opposed to filter) throws an error if multiple records are returned if menu.exists(): menu_name = menu[0].menu_name else: menu_name = None # Tracking tracking_type = TrackingType.objects.get( type='retail food tier price change') content_type = ContentType.objects.get_for_model(FoodPrice) input_params = \ { 'start': str(start), 'end': str(end), 'menu_id': menu_id, 'menu_name': menu_name, 'category_products': category_products, 'price': price, 'centers': centers } tracking_id = Tracking.objects.create(username=request.user, tracking_type=tracking_type, content_type=content_type, input_params=input_params) # FoodDataDao.updateFoodPrice(menu_id, category_products, centers, start, end, price, [category], request.user, tracking_id.tracking_id) return JsonResponse({'status': 1, 'msg': ''})
def update_food_price(menu_id, category_products, centers, start, end, price, category, user, tracking_id): user = User.objects.get(username=user) start = UDatetime.datetime_str_init( start).date() if start else UDatetime.now_local().date() end = UDatetime.datetime_str_init(start).date() if end else None FoodDataDao.updateFoodPrice(menu_id, category_products, centers, start, end, price, category, user, tracking_id) return
def submit(request, *args, **kwargs): action = request.GET.get('action') date = request.GET.get('date') price_type = request.GET.get('price_type') categories = request.GET.get('categories') categories = categories.split(',') categories = [int(category) for category in categories if category] # data init if not date: date = UDatetime.now_local().date() if not price_type: price_type = 'regular' if action == 'bulk pricing': if not categories: return JsonResponse({'status': 1, 'msg': ''}) price_symbol = request.GET.get('price-symbol') price = request.GET.get('price') price_unit = request.GET.get('price-unit') start = request.GET.get('start') end = request.GET.get('end') tiers = request.GET.getlist('tiers') if not tiers: tiers = get_tiers(date, price_type) if start: start = UDatetime.datetime_str_init(start).date() else: start = None if end: end = UDatetime.datetime_str_init(end).date() else: end = None price = [{ 'price_symbol': price_symbol, 'price_delta': UString.str2float(price), 'price_unit': price_unit, }] AlcoholReviseDAO.bulk_pricing(start, end, price, date, price_type, categories, tiers, request.user, tracking_id=None) return JsonResponse({'status': 1, 'msg': ''})
def update_opt(current_user, center_id, product_num, opt, start, end): center_obj = Centers.objects.get(center_id=center_id) product_obj = Product.objects.get(product_num=str(product_num)) # Tracking tracking_type = TrackingType.objects.get( type='product opt in/out change') content_type = ContentType.objects.get_for_model(ProductOpt) input_params = { 'opt': opt, 'center_id': center_id, 'start': str(start), 'end': str(end), 'product_num': product_num } tracking_id = Tracking.objects.create(username=current_user, tracking_type=tracking_type, content_type=content_type, input_params=input_params) # Tracking Change Report BSChangeReport.objects.create(tracking_id=tracking_id, username=current_user, center_id=center_obj, product_id=product_obj, effective_start=start, effective_end=end, price_old=None, price_new=None, is_bulk_change=True, opt=opt) # ProductOpt.objects \ .update_or_create( product_id=product_obj, center_id=center_obj, start=start, end=end, defaults={ 'opt': opt, 'action_user': current_user, 'tracking_id': tracking_id, 'action_time': UDatetime.now_local() } )
def get_all_schedules_sync_to_somax(cls): tasks = Tasks.objects.filter(current_status__in=cls.ready_for_schedule_tasks_status, sync_to_somax__in=['no', 'error'])\ .exclude(priority__in=['T', 'O']) tasks_record = pd.DataFrame.from_records( tasks.values('line', 'work_order', 'description', 'AOR__worker__name', 'estimate_hour', 'work_type', 'priority', 'create_date', 'current_status', 'workerscheduled__date', 'workerscheduled__name__somax_account', 'sync_to_somax').annotate( schedule_hour=Sum('workerscheduled__duration'))) tasks_record.rename_axis({'AOR__worker__name': 'AOR'}, axis=1, inplace=True) tasks_record.rename_axis({'workerscheduled__date': 'date'}, axis=1, inplace=True) tasks_record.rename_axis( {'workerscheduled__name__somax_account': 'worker'}, axis=1, inplace=True) if tasks_record.empty: return pd.DataFrame() tasks_record['schedule_hour'].fillna(timedelta(hours=0), inplace=True) tasks_record['schedule_hour'] = tasks_record['schedule_hour'].apply( lambda x: x.total_seconds() / 3600) now_date = UDatetime.now_local().date() tasks_record['OLD'] = tasks_record['create_date'].apply(lambda x: int( (now_date - x.date()).total_seconds() / (3600 * 24))) tasks_record.drop('create_date', axis=1, inplace=True) return tasks_record
def momentfeed_roll_over(cls, rolling_week=2, current_user=None): current_user = User.objects.get(username='******') records = MomentFeedAPI.get_all_centers() for index, row in records.iterrows(): center_obj = Centers.objects.filter(center_id=row['center_id']) if center_obj.exists(): center_obj = center_obj[0] else: continue start = row['start'] end = row['end'] if start and end: if datetime.time(0, 0) <= end <= datetime.time(4, 0): overnight = True else: overnight = False else: overnight = False OpenHours.objects.update_or_create(center_id=center_obj, DOW=row['dow'], defaults={ 'open_hour': start, 'end_hour': end, 'overnight': overnight, 'action_time': UDatetime.now_local(), 'action_user': current_user })
def product_opt_migrate(cls): start = dt(2018, 1, 1) productopt_objs = ProductOpt.objects.exclude(action_user=None) for productopt_obj in productopt_objs: product_id = productopt_obj.product_id.product_id center_obj = productopt_obj.center_id opt = productopt_obj.opt username = productopt_obj.action_user tracking_id = productopt_obj.tracking_id if opt == 'In': opt_oppo = 'Out' else: opt_oppo = 'In' if product_id == '105': product_obj = Product.objects.get(product_id='110') ProductOpt.objects.update_or_create(product_id=product_obj, center_id=center_obj, start=start, end=None, defaults={ 'opt': opt, 'action_user': username, 'action_time': UDatetime.now_local(), 'tracking_id': tracking_id }) product_obj_oppo = Product.objects.get(product_id='109') ProductOpt.objects.update_or_create( product_id=product_obj_oppo, center_id=center_obj, start=start, end=None, defaults={ 'opt': opt_oppo, 'action_user': username, 'action_time': UDatetime.now_local(), 'tracking_id': tracking_id }) elif product_id == '106': product_obj = Product.objects.get(product_id='113') ProductOpt.objects.update_or_create(product_id=product_obj, center_id=center_obj, start=start, end=None, defaults={ 'opt': opt, 'action_user': username, 'action_time': UDatetime.now_local(), 'tracking_id': tracking_id }) product_obj_oppo = Product.objects.get(product_id='112') ProductOpt.objects.update_or_create( product_id=product_obj_oppo, center_id=center_obj, start=start, end=None, defaults={ 'opt': opt_oppo, 'action_user': username, 'action_time': UDatetime.now_local(), 'tracking_id': tracking_id })
def edit(request, *args, **kwargs): current_user = request.user category_id = request.GET.get('category_id') category = request.GET.get('category') level = request.GET.get('level') price_type = request.GET.get('price_type') date = request.GET.get('date') field = request.GET.get('field') new_value = request.GET.get(field) old_value = request.GET.get('old_value') if not date: date = UDatetime.now_local().date() if not price_type: price_type = 'regular' if field.isdigit(): new_value = new_value.replace('$', '') old_value = old_value.replace('$', '') new_value = round(float(new_value), 2) old_value = round(float(old_value), 2) if new_value == '-': new_value = None if old_value == '-': old_value = None # Tracking # tracking_type = TrackingType.objects.get(type='retail food tier price change') tracking_type = None content_type = ContentType.objects.get_for_model(AlcoholTier) input_params = { 'new_price': new_value, 'old_price': old_value, 'category': category, 'level': level, 'price_typ': price_type, 'start': str(date), 'tier': field } tracking_id = Tracking.objects.create( username=current_user, tracking_type=tracking_type, content_type=content_type, input_params=input_params) category_id = AlcoholCategory.objects.get( category_id=category_id) AlcoholTier.objects \ .update_or_create( category_id=category_id, price_type=price_type, tier=field, defaults={ 'price': new_value, 'action_user': current_user, 'tracking_id': tracking_id } ) # Tracking Change Report description = 'Change category "{category}" level "{level}" tier "{tier}" price ' \ 'from "${price_old}" to "${price_new}"'\ .format(category=category, level=level, tier=field, price_old=old_value, price_new=new_value) AlcoholChangeReport.objects \ .update_or_create\ ( tracking_id=tracking_id, username=current_user, action_time=UDatetime.now_local(), product_id=None, menu=None, category=category, level=level, tier=field, description=description, price_old=old_value, price_new=new_value, start=date, end=None ) return JsonResponse({})
def product_roll_over(cls, rolling_week=2, current_user=None): start = UDatetime.now_local().date() end = start + rolling_week * timedelta(days=7) - timedelta(days=1) current_user = User.objects.get(username='******') center_ids = Centers.objects.filter(status='open').values_list( 'center_id', flat=True) # product_ids = Product.objects \ # .filter(status='active', report_type__in=cls.rollover_report_type).values_list('product_id', flat=True) # product_ids = Product.objects \ # .filter(status='active', report_type='Retail Bowling').values_list('product_id', flat=True) # product_ids = Product.objects \ # .filter(status='active', report_type='Retail Shoe').values_list('product_id', flat=True) product_ids = Product.objects \ .filter(status='active', report_type__in=['Retail Promos', 'Event Bowling', 'Event Shoe', 'Event Packages']).values_list('product_id', flat=True) # model = RetailBowlingPrice # model = RetailShoePrice model = ProductPrice product_ids = [ product_id for product_id in product_ids if product_id not in cls.product_rollover_opt_out ] # get last price last_price_records = DataDAO.LastPrice.get_last_price( product_ids, center_ids, start, perpetual_only=True) if last_price_records.empty: return last_price_records = last_price_records[[ 'center_id', 'product_id', 'price' ]] # init to_records to_date_range = UDatetime.date_range(start, end) if not to_date_range: return to_records_list = [{ 'center_id': center_id, 'product_id': product_id, 'date': date, 'DOW': DOW_choice[date.weekday()][0] } for center_id in center_ids for product_id in product_ids for date in to_date_range] to_records = pd.DataFrame(to_records_list) # get product schedule productschedule_obj = ProductSchedule.objects.filter( product_id__product_id__in=product_ids, status='active') productschedule_records = pd.DataFrame.from_records( productschedule_obj.values('product_id__product_id', 'DOW')) productschedule_records.rename( {'product_id__product_id': 'product_id'}, axis=1, inplace=True) productschedule_records.drop_duplicates(['product_id', 'DOW'], inplace=True) productschedule_records['available'] = True to_records = to_records.join(productschedule_records.set_index( ['product_id', 'DOW']), on=['product_id', 'DOW'], how='left') # Get product opt in / out productopt_records = ProductOptGet.get_productopt( product_ids, start, end, center_ids) to_records['date'] = to_records['date'].apply(lambda x: str(x)) productopt_records['date'] = productopt_records['date'].apply( lambda x: str(x)) to_records = to_records.join(productopt_records.set_index( ['center_id', 'product_id', 'date']), on=['center_id', 'product_id', 'date'], how='left') to_records = to_records[(to_records['available']) & (to_records['opt'] == 'In')] # get rollover price to_records = to_records.join(last_price_records.set_index( ['center_id', 'product_id']), on=['center_id', 'product_id'], how='left') # remove overlap from_price_obj = model.objects \ .filter( center_id__in=center_ids, product_id__in=product_ids, date__range=[start, end] ) \ .exclude(action_user=current_user) from_product_record = pd.DataFrame.from_records( from_price_obj.values('center_id', 'product_id', 'date', 'price')) if not from_product_record.empty: from_product_record.rename({'price': 'current_price'}, inplace=True, axis=1) to_records['date'] = to_records['date'].apply(lambda x: str(x)) from_product_record['date'] = from_product_record['date'].apply( lambda x: str(x)) result_record = to_records.join( from_product_record.set_index( ['center_id', 'product_id', 'date']), on=['center_id', 'product_id', 'date'], how='left', ) result_record = result_record[ result_record['current_price'].isnull()] else: result_record = to_records.copy() # remove NA price result_record = result_record[~result_record['price'].isna()] # remove rollover model.objects \ .filter( center_id__in=center_ids, product_id__in=product_ids, date__range=[start, end], action_user=current_user) \ .delete() # add rollover for index, row in result_record.iterrows(): center_obj = Centers.objects.get(center_id=row['center_id']) product_obj = Product.objects.get(product_id=row['product_id']) model.objects.create(date=row['date'], DOW=row['DOW'], center_id=center_obj, product_id=product_obj, product_name=product_obj.product_name, price=round(row['price'], 2), action_user=current_user)
def get_all_tasks_open(cls, pagination=False, page_size=None, offset=None, filters=None, sort=None, order=None): if sort and order: if sort == 'OLD': sort = 'create_date' elif sort == 'balance_hour': sort = 'estimate_hour' if order == 'desc': sort = '-' + sort else: sort = 'work_order' tasks = Tasks.objects.filter(current_status__in=cls.ready_for_schedule_tasks_status)\ .exclude(priority__in=['T', 'O']) \ .annotate(schedule_hour=Sum('workerscheduled__duration')) \ .order_by(sort) if filters: filters = ast.literal_eval(filters) if filters.get('work_order'): tasks = tasks.filter( work_order__contains=filters['work_order']) if filters.get('description'): tasks = tasks.filter( description__contains=filters['description']) if filters.get('estimate_hour'): try: est = float(filters['estimate_hour']) tasks = tasks.filter(estimate_hour__exact=timedelta( hours=est)) except Exception as e: pass if filters.get('AOR'): tasks = tasks.filter( AOR__worker__name__contains=filters['AOR']) if filters.get('work_type'): tasks = tasks.filter(work_type__exact=filters['work_type']) if filters.get('priority'): tasks = tasks.filter(priority__exact=filters['priority']) if filters.get('current_status'): tasks = tasks.filter( current_status__exact=filters['current_status']) if filters.get('sync_to_somax'): tasks = tasks.filter( sync_to_somax__exact=filters['sync_to_somax']) num = tasks.count() if pagination: paginator = Paginator( tasks, page_size, ) current_page = int(offset / page_size) + 1 tasks = paginator.page(current_page).object_list tasks_record = pd.DataFrame.from_records( tasks.values('line', 'work_order', 'description', 'AOR__worker__name', 'estimate_hour', 'work_type', 'priority', 'create_date', 'current_status', 'schedule_hour', 'sync_to_somax')) tasks_record.rename_axis({'AOR__worker__name': 'AOR'}, axis=1, inplace=True) if tasks_record.empty: return pd.DataFrame(), 0 tasks_record['schedule_hour'].fillna(timedelta(hours=0), inplace=True) tasks_record['balance_hour'] = tasks_record[ 'estimate_hour'] - tasks_record['schedule_hour'] tasks_record['schedule_hour'] = tasks_record['schedule_hour'].apply( lambda x: x.total_seconds() / 3600) tasks_record['estimate_hour'] = tasks_record['estimate_hour'].apply( lambda x: x.total_seconds() / 3600) tasks_record['balance_hour'] = tasks_record['balance_hour'].apply( lambda x: x.total_seconds() / 3600) now_date = UDatetime.now_local().date() tasks_record['OLD'] = tasks_record['create_date'].apply(lambda x: int( (now_date - x.date()).total_seconds() / (3600 * 24))) tasks_record.drop('create_date', axis=1, inplace=True) return tasks_record, num
def create_or_update_task(cls, work_order, created_by, description=None, work_type=None, current_status='Complete', line=None, shift=None, priority=None, create_date=None, current_status_somax='Complete', schedule_date_somax=None, actual_date_somax=None, estimate_hour=timedelta(hours=0), scheduled_hour=timedelta(hours=0), actual_hour=timedelta(hours=0), fail_code=None, completion_comments=None, equipment=None, aor=None, creator=None, assigned=None, pms=None, created_on=None, task_id=None, source='auto', document=None): if not create_date: create_date = UDatetime.now_local() if not created_on: created_on = UDatetime.now_local() if task_id: task_obj = Tasks.objects.update_or_create( id=task_id, defaults={ 'work_order': work_order, 'description': description, 'work_type': work_type, 'current_status': current_status, 'line': line, 'shift': shift, 'priority': priority, 'create_date': create_date, 'current_status_somax': current_status_somax, 'schedule_date_somax': schedule_date_somax, 'actual_date_somax': actual_date_somax, 'estimate_hour': estimate_hour, 'scheduled_hour': scheduled_hour, 'actual_hour': actual_hour, 'fail_code': fail_code, 'completion_comments': completion_comments, 'equipment': equipment, 'AOR': aor, 'creator': creator, 'assigned': assigned, 'PMs': pms, 'created_by': created_by, 'created_on': created_on, 'source': source, 'document': document }) else: task_obj = Tasks.objects.update_or_create( work_order=work_order, defaults={ 'description': description, 'work_type': work_type, 'current_status': current_status, 'line': line, 'shift': shift, 'priority': priority, 'create_date': create_date, 'current_status_somax': current_status_somax, 'schedule_date_somax': schedule_date_somax, 'actual_date_somax': actual_date_somax, 'estimate_hour': estimate_hour, 'scheduled_hour': scheduled_hour, 'actual_hour': actual_hour, 'fail_code': fail_code, 'completion_comments': completion_comments, 'equipment': equipment, 'AOR': aor, 'creator': creator, 'assigned': assigned, 'PMs': pms, 'created_by': created_by, 'created_on': created_on, 'source': source, 'document': document }) task_id = task_obj[0].id cls.sync_task_by_id(task_id) return task_obj[0]
def food_menu_master_load_processor(cls): file_path_food = os.path.join( BASE_DIR, 'RM/Centers/sample/config/master food.xlsx') food_records = pd.read_excel(file_path_food) food_records = food_records.where((pd.notnull(food_records)), None) effective_datetime = datetime.datetime(2018, 1, 1) menu_list = food_records['Menu'].unique() for menu in menu_list: Menu.objects.update_or_create(name=menu, ) food_records = pd.melt(food_records, id_vars=[ 'Product Id', 'Menu', 'Sell Type', 'Category', 'Product Description', 'Prod num', 'Start', 'End', 'Status', ], var_name='tier') food_records = food_records[food_records['value'].notnull()] for index, row in food_records.iterrows(): start = row['Start'] end = row['End'] product_num = row['Prod num'] if product_num: product_num = str(int(product_num)) else: product_num = None # load food product product_obj, exist = Product.objects.update_or_create( product_id=row['Product Id'], defaults={ 'product_name': row['Product Description'], 'product_num': product_num, 'readable_product_name': row['Product Description'], 'short_product_name': row['Product Description'], 'status': row['Status'] }) # load product schedule if not isinstance(start, pd.tslib.NaTType) or not isinstance( end, pd.tslib.NaTType): ProductSchedule.objects.update_or_create( product_id=product_obj, defaults={ 'start': row['Start'], 'end': row['End'], 'status': 'active', 'product_name': product_obj.product_name, 'action_time': UDatetime.now_local() }) menu = Menu.objects.get(name=row['Menu']) price = round(float(row['value']), 2) FoodMenuTable.objects.update_or_create(product=product_obj, menu=menu, tier=row['tier'], category=row['Category'], defaults={ 'price': price, 'status': 'active' })
def get_selections(cls, request, *args, **kwargs): selectType = request.GET.get('selectType') search = request.GET.get('search') menuId = request.GET.get('menu_id') start = request.GET.get('start') start = UDatetime.datetime_str_init( start).date() if start else UDatetime.now_local().date() if not search: result = [{ 'id': 'all', "text": 'All', }] else: result = [] if selectType == 'district': centers = Centers.objects.filter(status='open') \ .exclude(district=None) \ .exclude(district__contains='closed') if search: centers = centers.filter(district__contains=search) values = centers.values_list('district', flat=True).distinct() values = sorted(values) result += \ [ { 'id': value, "text": value, } for value in values ] elif selectType == 'region': centers = Centers.objects.filter(status='open') \ .exclude(region=None) \ .exclude(region__contains='closed') if search: centers = centers.filter(region__contains=search) values = centers.values_list('region', flat=True).distinct() values = sorted(values) result += \ [ { 'id': value, "text": value, } for value in values ] elif selectType == 'center_id': centers = Centers.objects.filter(status='open') if search: if search.isdigit(): centers = centers.filter(center_id__contains=search) else: centers = centers.filter(center_name__contains=search) centers = centers \ .order_by('center_id') \ .extra(select={'center_id': 'CAST(center_id AS INTEGER)'}) center_records = pd.DataFrame.from_records( centers.values( 'center_id', 'center_name', )) result += \ [ { 'id': row['center_id'], "text": str(row['center_id']) + '-' + str(row['center_name']), } for index, row in center_records.iterrows() ] elif selectType == 'menu_id': menus = Menu.objects.filter(status='active') if search: menus = menus.filter(menu_name__contains=search) menu_records = pd.DataFrame.from_records( menus.values( 'menu_id', 'menu_name', )) if not menu_records.empty: menu_records.sort_values(['menu_name'], inplace=True) result = [] result += \ [ { 'id': row['menu_id'], "text": row['menu_name'], } for index, row in menu_records.iterrows() ] elif selectType == 'category': if menuId: values = FoodPrice.objects \ .filter(menu_id=menuId) \ .exclude(Q(start__gt=start) | Q(end__lt=start) ) if search: values = values.filter(category__contains=search) values = values \ .values_list('category', flat=True) \ .distinct() else: values = [] result += \ [ { 'id': value, "text": value, } for value in values ] return JsonResponse({'status': 1, 'msg': '', 'results': result})
def get_columns(cls, request, centersOnly=False, *args, **kwargs): menuId = request.GET.get('menu_id') category = request.GET.get('category') start = request.GET.get('start') # Get all selection values district = request.GET.getlist('district') region = request.GET.getlist('region') center_id = request.GET.getlist('center_id') # Find if all in the selections if district and 'all' in district: district = [] if region and 'all' in region: region = [] if center_id and 'all' in center_id: center_id = [] # Remove empty string district = [item for item in district if item] region = [item for item in region if item] center_id = [item for item in center_id if item] # Filter centers centers = Centers.objects \ .filter(status='open') if district: centers = centers.filter(district__in=district) if region: centers = centers.filter(region__in=region) if center_id: centers = centers.filter(center_id__in=center_id) center_list = centers.values_list('center_id', flat=True) start = UDatetime.datetime_str_init( start).date() if start else UDatetime.now_local().date() centers = FoodPrice.objects \ .filter(status='active', menu__menu_id=menuId, center_id__in=center_list ) \ .exclude(Q(start__gt=start) | Q(end__lt=start) ) \ .values_list('center_id', flat=True).distinct() centers = sorted([int(center) for center in centers]) if centersOnly: return centers columns = \ [ { 'field': 'state', 'title': 'State', 'checkbox': True }, { 'field': 'menu', 'title': 'Menu', 'sortable': True, 'editable': False, 'align': 'center', 'vlign': 'center' }, { 'field': 'category', 'title': 'Category', 'sortable': True, 'editable': False, 'align': 'center', 'vlign': 'center' }, { 'field': 'food', 'title': 'Food', 'sortable': True, 'editable': False, 'align': 'center', 'vlign': 'center', 'filter': {'type': 'input'} }, { 'field': 'product_num', 'title': 'Prod Num', 'sortable': True, 'editable': False, 'align': 'center', 'vlign': 'center', 'filter': {'type': 'input'} }, # { # 'field': 'start', 'title': 'Start', 'sortable': True, 'editable': True, # 'align': 'center', 'vlign': 'center', 'filter': {'type': 'input'} # }, # { # 'field': 'end', 'title': 'End', 'sortable': True, 'editable': True, # 'align': 'center', 'vlign': 'center', 'filter': {'type': 'input'} # }, { 'field': 'product_id', 'title': 'product_id', 'visible': False, 'align': 'center', 'vlign': 'center', 'filter': {'type': 'input'} }, { 'field': 'menu_id', 'title': 'menu_id', 'visible': False, 'align': 'center', 'vlign': 'center', 'filter': {'type': 'input'} }, ] columns += [{ 'field': centerId, 'title': centerId, 'editable': True, 'align': 'center', 'vlign': 'center', } for centerId in centers] return JsonResponse({'status': 1, 'msg': '', 'columns': columns})
def export(request, *args, **kwargs): page_size = int(request.GET.get('limit')) offset = int(request.GET.get('offset')) filters = request.GET.get('filter') sort = request.GET.get('sort') order = request.GET.get('order') start = request.GET.get('start') end = request.GET.get('end') menu_id = request.GET.get('menu_id') file_type = request.GET.get('type') # Get all selection values category = request.GET.getlist('category') district = request.GET.getlist('district') region = request.GET.getlist('region') center_id = request.GET.getlist('center_id') # Find if all in the selections if category and 'all' in category: category = [] if district and 'all' in district: district = [] if region and 'all' in region: region = [] if center_id and 'all' in center_id: center_id = [] # Remove empty string category = [item for item in category if item] district = [item for item in district if item] region = [item for item in region if item] center_id = [item for item in center_id if item] start = UDatetime.datetime_str_init( start).date() if start else UDatetime.now_local().date() data, num = FoodDataDao.getFoodByCenter(menu_id, start, category, district, region, center_id, pagination=True, page_size=page_size, offset=offset, filters=filters, sort=sort, order=order, download=True) if file_type == 'json': response = json.dumps(data.to_dict(orient='records'), ensure_ascii=False) response = HttpResponse(response, content_type='application/json') response[ 'Content-Disposition'] = 'attachment; filename=export.json' elif file_type == 'csv': response = data.to_csv(index=False) response = HttpResponse(response, content_type='application/csv') response[ 'Content-Disposition'] = 'attachment; filename=export.csv' elif file_type == 'xlsx': response = io() xlwriter = pd.ExcelWriter(response) data.to_excel(xlwriter, index=False) xlwriter.save() xlwriter.close() response.seek(0) response = HttpResponse( response.read(), content_type= 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' ) response[ 'Content-Disposition'] = 'attachment; filename=export.xlsx' else: response = json.dumps([], ensure_ascii=False) response = HttpResponse(response, content_type='application/json') response[ 'Content-Disposition'] = 'attachment; filename=export.json' return response
def submit(cls, request, *args, **kwargs): price = request.GET.get('price') category_products = request.GET.getlist('category_products') if price and category_products and category_products != [ 'undefined---undefined' ]: menu_id = request.GET.get('menu_id') category = request.GET.get('category') start = request.GET.get('start') end = request.GET.get('end') priceSymbol = request.GET.get('price-symbol') priceUnit = request.GET.get('price-unit') price_ = request.GET.get('price') start = UDatetime.datetime_str_init( start).date() if start else UDatetime.now_local().date() end = UDatetime.datetime_str_init(end).date() if end else None category_products = [ category_product.split('---') for category_product in category_products ] category_products = [ (category, product_id) for category, product_id in category_products ] centers = Panel2.Table1.get_columns(request, centersOnly=True, *args, **kwargs) price = { 'price_symbol': priceSymbol, 'price': float(price_), 'unit': priceUnit } # Get Menu menu = Menu.objects.filter(menu_id=menu_id) if menu.exists(): menu_name = menu[0].menu_name else: menu_name = None # Tracking tracking_type = TrackingType.objects.get( type='retail food tier price change') content_type = ContentType.objects.get_for_model(FoodPrice) input_params = \ { 'start': str(start), 'end': str(end), 'menu_id': menu_id, 'menu_name': menu_name, 'category_products': category_products, 'price': price, 'centers': centers } tracking_id = Tracking.objects.create( username=request.user, tracking_type=tracking_type, content_type=content_type, input_params=input_params) # update_food_price.delay(menu_id, category_products, centers, start, end, price, category, request.user.username, tracking_id.tracking_id) # FoodDataDao.updateFoodPrice(menu_id, category_products, centers, start, end, price, category, request.user, tracking_id.tracking_id) response = Panel2.Table1.get_columns(request, *args, **kwargs) return response