def resources(request, *args, **kwargs): start = request.GET.get('start') end = request.GET.get('end') start = UDatetime.datetime_str_init(start) end = UDatetime.datetime_str_init(end, start, timedelta(days=1)) start_date = UDatetime.pick_date_by_one_date(start) end_date = UDatetime.pick_date_by_one_date(end) workers_df = WorkScheduleDataDAO.get_all_include_workers_by_date_range( start_date, end_date) response = [] if not workers_df.empty: workers_df.rename_axis( { 'name': 'title', 'balance': 'Avail' }, axis=1, inplace=True) response = workers_df.to_dict(orient='records') return JsonResponse(response, safe=False) else: return JsonResponse(response, safe=False)
def avail_dao(cls, start, end, worker_names=None, date_model='round'): avail = timedelta(hours=0) avail_deduct = timedelta(hours=0) if date_model == 'round': start_date = UDatetime.pick_date_by_one_date(start) end_date = UDatetime.pick_date_by_one_date(end) elif date_model == 'accurate': start_date = start end_date = end else: start_date = start end_date = end if worker_names: worker = Workers.objects.filter(id__in=worker_names) worker_avail = WorkerAvailable.objects.filter( date__range=[start_date, end_date], name__in=worker_names) else: worker_avail = WorkerAvailable.objects.filter( date__range=[start_date, end_date]) if worker_avail.exists(): pass
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 worker_submit(request, *args, **kwargs): command_type = request.GET.get('CommandType') start = request.GET.get('start') end = request.GET.get('end') worker_id = request.GET.get('resourceId') start = UDatetime.datetime_str_init(start) end = UDatetime.datetime_str_init(end, start, timedelta(hours=2)) start_date = UDatetime.pick_date_by_one_date(start) end_date = UDatetime.pick_date_by_one_date(end) worker = Workers.objects.get(id=worker_id) response = [] if command_type == 'ClearTasks': WorkScheduleReviseDAO.remove_schedule_by_date_range_and_worker( start_date, end_date, worker) elif command_type == 'ClearAll': WorkScheduleReviseDAO.remove_available_by_date_range_and_worker( start_date, end_date, worker) WorkScheduleReviseDAO.remove_schedule_by_date_range_and_worker( start_date, end_date, worker) 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 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 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 submit(request, *args, **kwargs): start = request.GET.get('Start') end = request.GET.get('End') start = UDatetime.datetime_str_init(start) end = UDatetime.datetime_str_init(end, start, timedelta(days=1)) SmartScheduler(request, start, end).run() return JsonResponse({})
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 add_worker_workers(request, *args, **kwargs): start = request.GET.get('start') end = request.GET.get('end') start = UDatetime.datetime_str_init(start) end = UDatetime.datetime_str_init(end, start, timedelta(days=1)) start_date = UDatetime.pick_date_by_one_date(start) end_date = UDatetime.pick_date_by_one_date(end) workers_df = WorkScheduleDataDAO.get_all_exclude_workers_by_date_range( start_date, end_date) workers_df_contractor = pd.DataFrame(columns=['id', 'text']) workers_df_contractor['id'] = workers_df[workers_df['type'] == 'contractor']['id'] workers_df_contractor['text'] = workers_df[ workers_df['type'] == 'contractor']['name'] if not workers_df_contractor.empty: workers_dict_contractor = workers_df_contractor.to_dict( orient='records') else: workers_dict_contractor = [] workers_df_employee = pd.DataFrame(columns=['id', 'text']) workers_df_employee['id'] = workers_df[workers_df['type'] == 'employee']['id'] workers_df_employee['text'] = workers_df[workers_df['type'] == 'employee']['name'] if not workers_df_employee.empty: workers_dict_employee = workers_df_employee.to_dict( orient='records') else: workers_dict_employee = [] response = [ { 'text': 'Contractor', 'children': workers_dict_contractor }, { 'text': 'Employee', 'children': workers_dict_employee }, ] return JsonResponse(response, safe=False)
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 balance_dao(cls, start, end, worker_names=None, date_model='round'): if date_model == 'round': start_date = UDatetime.pick_date_by_one_date(start) end_date = UDatetime.pick_date_by_one_date(end) elif date_model == 'accurate': start_date = start end_date = end else: start_date = start end_date = end if worker_names: worker = Workers.objects.filter(id__in=worker_names) worker_avail = WorkerAvailable.objects.filter( date__range=[start_date, end_date], name__in=worker_names) else: worker_avail = WorkerAvailable.objects.filter( date__range=[start_date, end_date])
def event_shoe_price_init(cls): to_date_range = UDatetime.date_range(cls.start, cls.end) product_ids = ['3101'] center_objs = Centers.objects.filter(status='open').exclude( bowling_event_tier=None) center_records = pd.DataFrame.from_records( center_objs.values('center_id', 'bowling_event_tier')) centers = center_records['center_id'].tolist() to_records_list = [{ 'center_id': center_id, 'product_id': product_id, 'date': date, 'DOW': DOW_choice[date.weekday()][0] } for center_id in centers for product_id in product_ids for date in to_date_range] to_records = pd.DataFrame(to_records_list) # get last price if not product_ids: return last_price_records = DataDAO.LastPrice.get_last_price(['115'], centers, cls.start.date()) if not last_price_records.empty: last_price_records = last_price_records[[ 'center_id', 'product_id', 'price' ]] last_price_records['product_id'] = '3101' to_records = to_records.join(last_price_records.set_index( ['center_id', 'product_id']), on=['center_id', 'product_id'], how='left') to_records.dropna(subset=['price'], inplace=True) # Load into database for index, row in to_records.iterrows(): center_obj = Centers.objects.get(center_id=row['center_id']) product_obj = Product.objects.get(product_id=row['product_id']) ProductPrice.objects \ .update_or_create( date=row['date'], DOW=row['DOW'], center_id=center_obj, product_id=product_obj, defaults={ 'price': round(row['price'], 2), 'perpetual': True, 'product_name': product_obj.product_name, } ) return
def bulk_price_change_task_from_price_change(start, end, product, DOW, price, centers, user, tracking_id): start = UDatetime.datetime_str_init(start).date() if not end: end = None else: end = UDatetime.datetime_str_init(end).date() user = User.objects.get(username=user) tracking_id = Tracking.objects.get(tracking_id=tracking_id) DataReviseDAO.pricing_new4(start, end, product, DOW, price, centers, user, tracking_id=tracking_id) return
def event_update(request, *args, **kwargs): start = request.GET.get('start') end = request.GET.get('end') resourceId = request.GET.get('resourceId') taskId = request.GET.get('taskId') workerscheduledId = request.GET.get('workerscheduledId') start = UDatetime.datetime_str_init(start) end = UDatetime.datetime_str_init(end, start, timedelta(hours=2)) date = UDatetime.pick_date_by_two_date(start, end) duration = end - start worker = Workers.objects.get(id__exact=resourceId) task = Tasks.objects.get(work_order__exact=taskId) available_id = WorkerAvailable.objects.filter( time_start__lte=start, time_end__gte=end, name__exact=worker) if available_id.count() > 0: available_id = available_id[0] WorkScheduleReviseDAO.update_or_create_schedule( request.user, start, end, date, duration, available_id, worker, task, schedule_id=workerscheduledId) response = [] return JsonResponse(response, safe=False)
def create_columns_by_date_range(cls, start, end, level=1): date_range = UDatetime.date_range(start, end) columns = [] for date in date_range: if level == 1: dow = DOW_choice[date.weekday()][0] date_str = date.strftime('%Y%m%d') pattern = \ [ { 'field': date_str, 'title': '{dow}<br/>{date}'.format(dow=dow.capitalize(), date=date.strftime('%Y-%m-%d')), 'colspan': 3, 'align': 'center' } ] elif level == 2: date_str = date.strftime('%Y%m%d') pattern = \ [ { 'field': '{date}-nonprime'.format(date=date_str), 'title': 'Non-Prime', 'sortable': True, 'editable': True, 'align': 'center' }, { 'field': '{date}-prime'.format(date=date_str), 'title': 'Prime', 'sortable': True, 'editable': True, 'align': 'center' }, { 'field': '{date}-premium'.format(date=date_str), 'title': 'Premium', 'sortable': True, 'editable': True, 'align': 'center' } ] else: pattern = [] columns += pattern return columns
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 sync_schedules_to_somax_spider(self): tasks_records = self.get_schedules_to_somax_spider() if tasks_records.empty: return None # dummy data # date = '2017/12/10' # assigned = 'BBUGRNATU' # work_orders = ['17001030', '17003808'] self.driver.get(self.somax_label_scheduling_url) current_url = self.driver.current_url if current_url == self.somax_login_url: self.login() self.get_and_ready(self.somax_label_scheduling_url) # check date date_str = self.driver.find_element_by_id( self.somax_label_scheduling_assigned_input_id).text dt_format = UDatetime.check_date_format(date_str) if dt_format == 'YY/mm/dd': tasks_records['date'] = tasks_records['date'].apply( lambda x: '{dt.year}/{dt.month}/{dt.day}'.format(dt=x)) elif dt_format == 'mm/dd/YY': tasks_records['date'] = tasks_records['date'].apply( lambda x: '{dt.month}/{dt.day}/{dt.year}'.format(dt=x)) else: tasks_records['date'] = tasks_records['date'].apply( lambda x: '{dt.year}/{dt.month}/{dt.day}'.format(dt=x)) groups = tasks_records['group'].unique() for group in groups: tasks_group = tasks_records[tasks_records['group'] == group] self.sync_schedule_to_somax_spider(tasks_group) # self.sync_schedule_to_somax_spider('BBUGRNATU', '2017/12/10', ['17001030', '17003808']) # self.driver.quit() # if not self.DISPLAY: # self.display.stop() return True
def scheduled_substract(cls, available): available_df = pd.DataFrame(available.__dict__, index=[0]) scheduled = WorkerScheduled.objects.filter(available_id=available) # update available by scheduled tasks if scheduled.exists(): scheduled_df = pd.DataFrame.from_records(scheduled.values()) for index_scheduled, row_scheduled in scheduled_df.iterrows(): scheduled_start = row_scheduled['time_start'] scheduled_end = row_scheduled['time_end'] for index_avail, row_avail in available_df.iterrows(): available_start = row_avail['time_start'] available_end = row_avail['time_end'] available_new = UDatetime.remove_overlap( available_start, available_end, scheduled_start, scheduled_end) available_start = available_new[0][0].astimezone('UTC') available_end = available_new[0][1].astimezone('UTC') available_df.set_value(index_avail, 'time_start', available_start) available_df.set_value(index_avail, 'time_end', available_end) if len(available_new) == 2: available_start_addition = available_new[1][0] available_end_addition = available_new[1][1] available_addition_row = available_df.iloc[index_avail] available_addition_row.set_value( 'time_start', available_start_addition.astimezone('UTC')) available_addition_row.set_value( 'time_end', available_end_addition.astimezone('UTC')) available_df = available_df.append( available_addition_row, ignore_index=True) available_df.sort_values(['date', 'time_start'], inplace=True) return available_df
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 downday_str_parser(string, year, week_number): regex = re.compile( r'(?P<weekday>[a-zA-Z]+)\s*(?P<hour>[0-9]+):(?P<min>[0-9]+)') parts = regex.match(string) if parts: parts = parts.groupdict() else: return None str_new = '{year}-{week_number}-{weekday}-{hour}-{min}' \ .format(year=year, week_number=week_number, weekday=parts['weekday'], hour=parts['hour'], min=parts['min'] ) downday = UDatetime.localize(dt.strptime(str_new, '%Y-%W-%a-%H-%M')) return downday
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 is_downday(cls, start, end): from configuration.WorkScheduleConstants import PMs bread_downday_start = cls.downday_str_parser(PMs.Bread.Downdays.start, start.year, start.isocalendar()[1]) bread_downday_end = cls.downday_str_parser(PMs.Bread.Downdays.end, start.year, start.isocalendar()[1] + 1) em_downday_start = cls.downday_str_parser(PMs.EM.Downdays.start, start.year, start.isocalendar()[1]) em_downday_end = cls.downday_str_parser(PMs.EM.Downdays.end, start.year, start.isocalendar()[1]) overlap = UDatetime.get_overlap(start, end, bread_downday_start, bread_downday_end) if overlap.total_seconds() == 0: return False else: return True
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 submit(request, *args, **kwargs): # Tracking current_user = request.user start = request.GET.get('start') end = request.GET.get('end') product = request.GET.get('product') DOW = request.GET.getlist('DOW') centers = request.GET.get('centers') centers = centers.split(',') centers = [center.replace('*', '') for center in centers] last_price_from_change = True # Non task date init # 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() start = UDatetime.datetime_str_init(start).date() if not end: end = None else: end = UDatetime.datetime_str_init(end).date() if product == 'retail bowling': np_price_symbol = request.GET.get('np-price-symbol') np_price = request.GET.get('np-price') np_price_unit = request.GET.get('np-price-unit') np_price_base = request.GET.get('np-price-base') primewk_price_symbol = request.GET.get('primewk-price-symbol') primewk_price = request.GET.get('primewk-price') primewk_price_unit = request.GET.get('primewk-price-unit') primewk_price_base = request.GET.get('primewk-price-base') primewkd_price_symbol = request.GET.get( 'primewkd-price-symbol') primewkd_price = request.GET.get('primewkd-price') primewkd_price_unit = request.GET.get('primewkd-price-unit') primewkd_price_base = request.GET.get('primewkd-price-base') premium_price_symbol = request.GET.get('premium-price-symbol') premium_price = request.GET.get('premium-price') premium_price_unit = request.GET.get('premium-price-unit') premium_price_base = request.GET.get('premium-price-base') price = [ { 'product_id': '108', 'price_symbol': np_price_symbol, 'price_delta': UString.str2float(np_price), 'price_unit': np_price_unit, 'product_id_base': np_price_base }, { 'product_id': '110', 'price_symbol': primewk_price_symbol, 'price_delta': UString.str2float(primewk_price), 'price_unit': primewk_price_unit, 'product_id_base': primewk_price_base }, { 'product_id': '111', 'price_symbol': primewkd_price_symbol, 'price_delta': UString.str2float(primewkd_price), 'price_unit': primewkd_price_unit, 'product_id_base': primewkd_price_base }, { 'product_id': '113', 'price_symbol': premium_price_symbol, 'price_delta': UString.str2float(premium_price), 'price_unit': premium_price_unit, 'product_id_base': premium_price_base }, ] # Tracking tracking_type = TrackingType.objects.get( type='bulk retail bowling price change') content_type = ContentType.objects.get_for_model( RetailBowlingPrice) elif product == 'retail shoe': wk_price_symbol = request.GET.get('wk-price-symbol') wk_price = request.GET.get('wk-price') wk_price_unit = request.GET.get('wk-price-unit') wk_price_base = request.GET.get('wk-price-base') wknd_price_symbol = request.GET.get('wknd-price-symbol') wknd_price = request.GET.get('wknd-price') wknd_price_unit = request.GET.get('wknd-price-unit') wknd_price_base = request.GET.get('wknd-price-base') price = [ { 'product_id': '114', 'price_symbol': wk_price_symbol, 'price_delta': UString.str2float(wk_price), 'price_unit': wk_price_unit, 'product_id_base': wk_price_base }, { 'product_id': '115', 'price_symbol': wknd_price_symbol, 'price_delta': UString.str2float(wknd_price), 'price_unit': wknd_price_unit, 'product_id_base': wknd_price_base }, ] # Tracking tracking_type = TrackingType.objects.get( type='bulk retail shoes price change') content_type = ContentType.objects.get_for_model( RetailShoePrice) elif product == 'after party friday': friday8PM_price_symbol = request.GET.get('8pm-price-symbol') friday8PM_price = request.GET.get('8pm-price') friday8PM_price_unit = request.GET.get('8pm-price-unit') friday8PM_price_base = request.GET.get('8pm-price-base') friday9PM_price_symbol = request.GET.get('9pm-price-symbol') friday9PM_price = request.GET.get('9pm-price') friday9PM_price_unit = request.GET.get('9pm-price-unit') friday9PM_price_base = request.GET.get('9pm-price-base') friday10PM_price_symbol = request.GET.get('10pm-price-symbol') friday10PM_price = request.GET.get('10pm-price') friday10PM_price_unit = request.GET.get('10pm-price-unit') friday10PM_price_base = request.GET.get('10pm-price-base') friday11PM_price_symbol = request.GET.get('11pm-price-symbol') friday11PM_price = request.GET.get('11pm-price') friday11PM_price_unit = request.GET.get('11pm-price-unit') friday11PM_price_base = request.GET.get('11pm-price-base') price = [ { 'product_id': '2146481686', 'price_symbol': friday8PM_price_symbol, 'price_delta': UString.str2float(friday8PM_price), 'price_unit': friday8PM_price_unit, 'product_id_base': friday8PM_price_base }, { 'product_id': '2146532909', 'price_symbol': friday9PM_price_symbol, 'price_delta': UString.str2float(friday9PM_price), 'price_unit': friday9PM_price_unit, 'product_id_base': friday9PM_price_base }, { 'product_id': '2146507303', 'price_symbol': friday10PM_price_symbol, 'price_delta': UString.str2float(friday10PM_price), 'price_unit': friday10PM_price_unit, 'product_id_base': friday10PM_price_base }, { 'product_id': '2146481687', 'price_symbol': friday11PM_price_symbol, 'price_delta': UString.str2float(friday11PM_price), 'price_unit': friday11PM_price_unit, 'product_id_base': friday11PM_price_base }, ] # Tracking tracking_type = TrackingType.objects.get( type='bulk retail promos price change') content_type = ContentType.objects.get_for_model(ProductPrice) else: price_symbol = request.GET.get('price-symbol') price = request.GET.get('price') price_unit = request.GET.get('price-unit') price = [{ 'product_id': product, 'price_symbol': price_symbol, 'price_delta': UString.str2float(price), 'price_unit': price_unit, 'product_id_base': product }] # Tracking tracking_type = TrackingType.objects.get( type='bulk retail promos price change') content_type = ContentType.objects.get_for_model(ProductPrice) if not last_price_from_change: if not DOW: DOW = [dow[0] for dow in DOW_choice] # Tracking input_params = \ { 'start': str(start), 'end': str(end), 'product': product, 'DOW': DOW, 'price': price, 'centers': centers } tracking_id = Tracking.objects.create(username=current_user, tracking_type=tracking_type, content_type=content_type, input_params=input_params) # msg = '' if price: if last_price_from_change: bulk_price_change_task_from_price_change.delay( start, end, product, DOW, price, centers, request.user.username, tracking_id=tracking_id.tracking_id) # DataReviseDAO.pricing_new4(start, end, product, DOW, price, centers, request.user, # tracking_id=tracking_id) else: #currently not being used bulk_price_change_task.delay( start, end, product, DOW, price, centers, request.user.username, tracking_id=tracking_id.tracking_id) # DataReviseDAO.pricing_new3(start, end, product, DOW, price, centers, request.user, # start_report, end_report, tracking_id=tracking_id) msg = "RMS is updating your price changes. Price changes for all centers may take up to 15 mins. " \ "Subsequently the changes will be displayed in the 'Change Report'." return JsonResponse({'status': 1, 'msg': msg})
def export(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') file_type = request.GET.get('type') as_of_date = UDatetime.datetime_str_init(as_of_date).date() pagination = True if page_size: page_size = int(page_size) if offset: offset = int(offset) if product == 'retail bowling': product_ids = ProductChoice.retail_bowling_ids_new_short elif product == 'retail shoe': product_ids = ProductChoice.retail_shoe_product_ids_new elif product == 'after party friday': product_ids = [ '2146481686', '2146532909', '2146507303', '2146481687' ] elif product: product_ids = [product] else: product_ids = ProductChoice.retail_bowling_ids_new_short data, num = 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, lastPriceSplit=True, columns=[ 'center_name', 'region', 'district', 'brand', 'time_zone', 'center_type' ], as_of_date=as_of_date) # data = data.where((pd.notnull(data)), "") data.columns = map(str.capitalize, data.columns) 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' # elif type == 'excel': # writer = pd.ExcelWriter('export.xlsx') # response = data.to_excel(writer) # writer.save() # response = HttpResponse(response, content_type='application/vnd.ms-excel') # 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 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') as_of_date = UDatetime.datetime_str_init(as_of_date).date() pagination = True if page_size: page_size = int(page_size) if offset: offset = int(offset) if product == 'retail bowling': product_ids = ProductChoice.retail_bowling_ids_new_short last_price_from_change = True elif product == 'retail shoe': product_ids = ProductChoice.retail_shoe_product_ids_new last_price_from_change = True elif product == 'after party friday': product_ids = [ '2146481686', '2146532909', '2146507303', '2146481687' ] last_price_from_change = True elif product: product_ids = [product] last_price_from_change = True else: product_ids = ProductChoice.retail_bowling_ids_new_short last_price_from_change = True 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=last_price_from_change, as_of_date=as_of_date) # 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 submit(request, *args, **kwargs): # Tracking current_user = request.user start = request.GET.get('start') end = request.GET.get('end') product = request.GET.get('product') DOW = request.GET.getlist('DOW') centers = request.GET.get('centers') centers = centers.split(',') centers = [center.replace('*', '') for center in centers] start = UDatetime.datetime_str_init(start).date() if not end: end = None else: end = UDatetime.datetime_str_init(end).date() price = [] if product == 'event bowling': for bowling_product_id in ProductChoice.event_bowling_product_ids: x_price_symbol = request.GET.get( '{product_id}-price-symbol'.format( product_id=bowling_product_id)) x_price = request.GET.get('{product_id}-price'.format( product_id=bowling_product_id)) x_price_unit = request.GET.get( '{product_id}-price-unit'.format( product_id=bowling_product_id)) x_price_base = request.GET.get( '{product_id}-price-base'.format( product_id=bowling_product_id)) price += [ { 'product_id': bowling_product_id, 'price_symbol': x_price_symbol, 'price_delta': UString.str2float(x_price), 'price_unit': x_price_unit, 'product_id_base': x_price_base }, ] elif product == 'event shoe': product_id = '3101' price_symbol = request.GET.get('price-symbol') price = request.GET.get('price') price_unit = request.GET.get('price-unit') price = [{ 'product_id': product_id, 'price_symbol': price_symbol, 'price_delta': UString.str2float(price), 'price_unit': price_unit, 'product_id_base': product_id }] elif product == 'event basic packages': for product_id in ProductChoice.event_basic_packages_product_ids: x_price_symbol = request.GET.get( '{product_id}-price-symbol'.format( product_id=product_id)) x_price = request.GET.get( '{product_id}-price'.format(product_id=product_id)) x_price_unit = request.GET.get( '{product_id}-price-unit'.format( product_id=product_id)) x_price_base = request.GET.get( '{product_id}-price-base'.format( product_id=product_id)) price += [ { 'product_id': product_id, 'price_symbol': x_price_symbol, 'price_delta': UString.str2float(x_price), 'price_unit': x_price_unit, 'product_id_base': x_price_base }, ] # Tracking tracking_type = TrackingType.objects.get( type='bulk retail bowling price change') content_type = ContentType.objects.get_for_model(ProductPrice) # if not DOW: # DOW = [dow[0] for dow in DOW_choice] # Tracking input_params = \ { 'start': str(start), 'end': str(end), 'product': product, 'DOW': DOW, 'price': price, 'centers': centers } tracking_id = Tracking.objects.create(username=current_user, tracking_type=tracking_type, content_type=content_type, input_params=input_params) msg = '' if price: # DataReviseDAO.pricing_new4(start, end, product, DOW, price, centers, request.user, # tracking_id=tracking_id) bulk_price_change_task_from_price_change.delay( start, end, product, DOW, price, centers, request.user.username, tracking_id=tracking_id.tracking_id) msg = "RMS is updating your price changes. Price changes for all centers may take up to 15 mins. " \ "Subsequently the changes will be displayed in the 'Change Report'." return JsonResponse({'status': 1, 'msg': msg})