def list_wards(request): """ API get list Wards to select \n Parameters for this api : Có thể bỏ trống hoặc không gửi lên - code -- text - province_code -- text - district_code -- text """ queryset = QrWards.objects.values('id', 'wards_code', 'wards_name') code = request.GET.get('code', None) province_code = request.GET.get('province_code', None) district_code = request.GET.get('district_code', None) if code is not None and code != '': code = unidecode(format_string(code)) queryset = queryset.filter( Q(wards_name__unaccent__icontains=code) | Q(wards_code__icontains=code)) if province_code is not None and province_code != '': province_code = format_string(province_code) queryset = queryset.filter(province_code=province_code) if district_code is not None and district_code != '': district_code = format_string(district_code) queryset = queryset.filter(district_code=district_code) queryset = queryset.order_by('wards_name')[0:settings.PAGINATE_BY] data = [{ 'id': wards['id'], 'code': wards['wards_code'], 'name': wards['wards_name'] } for wards in queryset] return successful_response(data)
def count_terminal_30_days_before_heatmap(request): today = date.today() date_list = [] hour_list = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23] for i in range(0, 14): date_list.append((today - timedelta(days=14) + timedelta(days=i)).strftime("%d/%m/%Y")) with connection.cursor() as cursor: cursor.execute(''' select count(*),date(created_date) as terminal_date, extract(hour from created_date) as terminal_hour from terminal where created_date > current_date - interval '14 days' and created_date < current_date group by terminal_date,terminal_hour order by date(created_date) asc ''') columns = [col[0] for col in cursor.description] data_cursor = [ dict(zip(columns, row)) for row in cursor.fetchall() ] data = [] for item in data_cursor: data.append([ date_list.index(str(item['terminal_date'].strftime("%d/%m/%Y"))), hour_list.index(item['terminal_hour']), item['count'] ]) return successful_response({ 'data': data, 'date_list': date_list, 'hour_list': hour_list })
def list_terminals(request): """ API get list Terminal to select \n Parameters for this api : Có thể bỏ trống hoặc không gửi lên - name -- text - merchant_id -- number """ queryset = Terminal.objects.terminal_un_register_vnpayment() if request.user.is_superuser is False: if request.user.is_area_manager or request.user.is_sale_admin: provinces = get_provinces_viewable_queryset(request.user) queryset = queryset.filter(province_code__in=provinces.values('province_code')) else: shops = get_shops_viewable_queryset(request.user) queryset = queryset.filter(shop__in=shops) name = request.GET.get('name', None) merchant_id = request.GET.get('merchant_id', None) if name is not None and name != '': queryset = queryset.filter(Q(terminal_id__icontains=name) | Q(terminal_name__icontains=name)) if merchant_id is not None and merchant_id != '': queryset = queryset.filter(merchant_id=merchant_id) queryset = queryset.order_by('terminal_name')[0:settings.PAGINATE_BY] data = [{'id': terminal.id, 'name': terminal.terminal_id + ' - ' + terminal.terminal_name} for terminal in queryset] return successful_response(data)
def retrieve(self, request, pk): """ API get detail user """ user = User.objects.filter(pk=pk).first() if user is None: return custom_response(Code.USER_NOT_FOUND) user_permissions = user.user_permissions.all() group_permissions = Permission.objects.filter(group__user=user).all() areas, teams = [], [] for item in user.area_set.all(): area = {'id': item.id, 'name': item.name, 'code': item.code} areas.append(area) for item in user.team_set.all(): team = {'id': item.id, 'name': item.name, 'code': item.code} teams.append(team) data = { 'user': AccountSerializer(user).data, 'areas': areas, 'teams': teams, 'user_permissions': PermissionSerializer(user_permissions, many=True).data, 'group_permissions': PermissionSerializer(group_permissions, many=True).data, } return successful_response(data)
def get_count_shop_30_days_before(request): shop_count = Shop.objects.filter(activated=1).count() with connection.cursor() as cursor: cursor.execute(''' select count(*), date(created_date) from shop where created_date > current_date - interval '30 days' group by date(created_date) order by date(created_date) asc ''') columns = [col[0] for col in cursor.description] data_cursor = [dict(zip(columns, row)) for row in cursor.fetchall()] data_date = [] data_value = [] today = 0 for item in data_cursor: if str(item['date']) == str(date.today().strftime("%Y-%m-%d")): today = item['count'] continue data_date.append(str(item['date'].strftime("%d/%m/%Y"))) data_value.append(item['count']) return successful_response({ 'data': { 'data_date': data_date, 'data_value': data_value }, 'today': today, 'shop_count': shop_count })
def list_merchants(request): """ API get list Merchant to select \n Parameters for this api : Có thể bỏ trống hoặc không cần gửi lên - code -- text """ queryset = Merchant.objects.values('id', 'merchant_code', 'merchant_name', 'merchant_brand') if request.user.is_superuser is False: shops = get_shops_viewable_queryset(request.user) queryset = queryset.filter(pk__in=shops.values('merchant')) code = request.GET.get('code', None) if code is not None and code != '': queryset = queryset.filter( Q(merchant_code__icontains=code) | Q(merchant_brand__icontains=code)) queryset = queryset.order_by('merchant_brand')[0:settings.PAGINATE_BY] data = [{ 'id': merchant['id'], 'code': merchant['merchant_code'] + ' - ' + merchant['merchant_brand'] } for merchant in queryset] return successful_response(data)
def get_list_titles(request): """ API get list Title to select \n Parameters for this api : Có thể bỏ trống hoặc không gửi lên - code -- text """ queryset = SalePromotionTitle.objects.all() code = request.GET.get('code', None) show_promotion_reset = request.GET.get('show_promotion_reset', None) if code is not None and code != '': queryset = queryset.filter(code__icontains=code) if show_promotion_reset is not None and show_promotion_reset != '': pass else: queryset = queryset.filter(reset_data_date__isnull=True) queryset = queryset.order_by('code')[0:settings.PAGINATE_BY] data = [{ 'id': title.id, 'content': title.code + ' - ' + (title.description if title.description else 'N/A') } for title in queryset] return successful_response(data)
def model_permissions(request): """ API get list model-permissions \n """ queryset = Permission.objects.all().order_by('id') model_permissions = dict() for permission in queryset: print(f'Permission: {permission.id}') if permission.content_type.model not in model_names: continue item = { 'id': permission.id, 'name': permission.name, 'codename': permission.codename } if permission.content_type.model in model_permissions: permissions = model_permissions[permission.content_type.model] else: permissions = [] permissions.append(item) model_permissions[permission.content_type.model] = permissions return successful_response( collections.OrderedDict(sorted(model_permissions.items())))
def list_type_proportion_kpi_team(request): """ API get list loại tỷ trọng KPI Team """ data = [] for item in ProportionKpiTeamType.CHOICES: data.append({"type": item[0], "type_name": item[1]}) return successful_response(data)
def list_contract_durations(request): """ API get list thời hạn HĐ """ data = [] for item in ExchangePointPos365.objects.order_by('id').all(): data.append({"code": item.type, "description": item.name}) return successful_response(data)
def retrieve(self, request, pk): pos365 = get_object_or_404(Pos365, pk=pk) contract_start_date = formats.date_format(pos365.contract_start_date, "SHORT_DATE_FORMAT") \ if pos365.contract_start_date else '' staff = pos365.staff.email if pos365.staff is not None else None team = pos365.team.code if pos365.team is not None else None if pos365.contract_duration is not None: contract_duration_data = ExchangePointPos365.objects.get( type=pos365.contract_duration) else: contract_duration_data = None return successful_response({ 'id': pos365.id, 'code': pos365.code, 'contract_duration': contract_duration_data.name, 'contract_url': pos365.contract_url, 'contract_product_quantity': pos365.contract_product_quantity, 'contract_product_series': pos365.contract_product_series, 'contract_revenue': pos365.contract_revenue, 'contract_note': pos365.contract_note, 'contract_file': { 'name': os.path.basename(pos365.contract_file.name), 'url': str(pos365.contract_file.url), } if pos365.contract_file else None, 'staff': staff, 'team': team, 'contract_start_date': contract_start_date, 'contract_coefficient': pos365.contract_coefficient, 'point': (contract_duration_data.point * pos365.contract_coefficient) / 100 if contract_duration_data else 0, 'customer_merchant': pos365.customer_merchant, 'customer_name': pos365.customer_name, 'customer_phone': pos365.customer_phone, 'customer_address': pos365.customer_address, 'customer_province': pos365.customer_province.province_name if pos365.customer_province else None, })
def create(self, request): """ API tạo mới và cập nhật quy đổi point Pos365 \n Giá trị type_code lấy từ API /api/pos365s/list-contract-durations Request body for this api : Không được bỏ trống \n { "exchange_point_pos365s": [ { "type_code": 0, "point": 1 }, { "type_code": 1, "point": 2 } ] } """ try: body = json.loads(request.body) exchange_point_pos365s = body.get('exchange_point_pos365s') type_code_list = [] for i in Pos365ContractDuration.CHOICES: type_code_list.append(i[0]) validate_type_code = [] for item in exchange_point_pos365s: if item['type_code'] in validate_type_code: return custom_response(Code.INVALID_BODY, 'type_code is duplicate') else: validate_type_code.append(item['type_code']) if item['type_code'] not in type_code_list: return custom_response(Code.INVALID_BODY, 'type_code Invalid') if not isinstance(item['point'], float) and not isinstance( item['point'], int): return custom_response(Code.INVALID_BODY, 'point Invalid') for update_item in exchange_point_pos365s: ExchangePointPos365.objects.get_or_create( type=update_item['type_code']) ExchangePointPos365.objects.filter( type=update_item['type_code']).update( point=update_item['point']) return successful_response( 'Update or create ExchangePointPos365 success') except Exception as e: logging.error('Create ExchangePointPos365 exception: %s', e) return custom_response(Code.INTERNAL_SERVER_ERROR)
def user_info(request): """ API get user information \n """ user = request.user if user is None: return custom_response(Code.PERMISSION_DENIED) return successful_response(UserSerializer(user).data)
def create_from_terminal(request): if request.method == 'POST': terminal_id = request.POST.get('terminal_id', None) address = request.POST.get('address', None) street = request.POST.get('street', None) auto_create = request.POST.get('auto_create', None) terminal = Terminal.objects.get(pk=int(terminal_id)) elif request.method == 'OTHER': terminal = request.terminal address = request.address street = request.street else: return custom_response(Code.NOT_IMPLEMENTED) staff = None staff_of_chain = None merchant = terminal.merchant if merchant is not None: staff = merchant.get_staff() if staff is not None: team = staff.team if team is not None and team.type != TeamType.TEAM_SALE: staff_of_chain = merchant.get_staff() shop = Shop(merchant=terminal.merchant, name=conditional_escape(terminal.terminal_name), address=conditional_escape(address), province_id=terminal.get_province().id if (terminal.get_province() is not None) else None, district_id=terminal.get_district().id if (terminal.get_district() is not None) else None, wards_id=terminal.get_wards().id if (terminal.get_wards() is not None) else None, street=conditional_escape(street), created_by=request.user) shop.save() terminal.shop = shop terminal.save() if staff is not None: shop.staff_create(staff.id) if staff_of_chain is not None: shop.staff_of_chain_create(staff.id) if request.method == 'OTHER': return True data = {'shop_id': shop.pk} return successful_response(data)
def reset_data(request, pk): """ API delete SalePromotion by title_id """ if SalePromotionTitle.objects.filter(id=pk).first() is None: return custom_response(Code.PROMOTION_NOT_FOUND) SalePromotion.objects.filter(title_id=pk).delete() SalePromotionTitle.objects.filter(id=pk).update( reset_data_date=datetime.datetime.now(), updated_by=request.user) return successful_response()
def assign_ter_to_shop(request): ter_id = request.POST.get('ter_id') shop_id = request.POST.get('shop_id') terminal = get_object_or_404(Terminal, pk=ter_id) shop = get_object_or_404(Shop, pk=shop_id) if shop.merchant != terminal.merchant: return custom_response(Code.DATA_ERROR, "Shop và terminal không cùng merchant") else: terminal.shop = shop terminal.save() return successful_response({'id': shop.id})
def get_data_kpi_yourself(request): data = { 'target_kpi': 0, 'count_shop_new': 0, 'count_shop_s10': 0, 'point_shop_s10': 0, 'count_contract': 0, 'point_contract': 0, 'point_promotion_form': 0, 'point_other': 0 } kpi = Kpi.objects.filter(email=request.user.email, month=datetime.now().month, year=datetime.now().year).first() if kpi is not None: data['target_kpi'] = kpi.kpi_target data['point_promotion_form'] = kpi.kpi_point_lcc data['point_other'] = kpi.kpi_point_other contract_pos365s = Pos365.objects.filter( staff__email=request.user.email).all() data['count_contract'] = contract_pos365s.count() if data['count_contract'] != 0: exchange_points = {} for exchange_point_pos365 in ExchangePointPos365.objects.all(): exchange_points[ exchange_point_pos365.type] = exchange_point_pos365.point for contract in contract_pos365s: if exchange_points[contract.contract_duration] is not None: data['point_contract'] = data[ 'point_contract'] + exchange_points[ contract. contract_duration] * contract.contract_coefficient / 100 shop_list = [] for shop in Shop.objects.filter( created_date__gte=get_day_22_previous_month()).all().values('id'): shop_list.append(shop['id']) shop_news = ShopCube.objects.filter(shop_id__in=shop_list, number_of_tran_last_m__lt=10).all() data['count_shop_new'] = shop_news.count() for shop_new in shop_news: if (shop_new.number_of_tran_acm + shop_new.number_of_tran_last_m) >= 10: data['count_shop_s10'] += 1 data[ 'point_shop_s10'] = data['count_shop_s10'] * COEFFICIENT_POINT_SHOP_S10 return successful_response(data)
def export(request): """ API export data Sale Promotion Form \n Parameters for this api : Có thể bỏ trống hoặc không gửi lên - title_id -- integer - terminal_id -- text - shop_code -- text - team_id -- integer - staff_id -- integer - status -- number in {0, 1, 2, 3} """ file_path = render_excel(request) return successful_response(file_path)
def export(request): """ API export data Merchant \n Parameters for this api : Có thể bỏ trống hoặc không gửi lên - merchant_text -- text - area_id -- interger - province_id -- interger - status -- number in {-1,1,2,3,4,5,6} - from_date -- dd/mm/yyyy - to_date -- dd/mm/yyyy """ file_path = render_excel(request) return successful_response(file_path)
def retrieve(self, request, pk): """ API get detail account_group_permission """ custom_group = CustomGroup.objects.filter(pk=pk).first() if custom_group is None: return custom_response(Code.GROUP_NOT_FOUND) permissions = [] for permission in custom_group.permissions.all(): element = { 'id': permission.id, 'name': permission.name, 'codename': permission.codename, 'content_type': { 'id': permission.content_type.id, 'model': permission.content_type.model } } permissions.append(element) data = { 'id': custom_group.id, 'name': custom_group.name, 'status': custom_group.status, 'created_date': formats.date_format(custom_group.created_date, "SHORT_DATETIME_FORMAT") if custom_group.created_date else '', 'created_by': custom_group.created_by.username if custom_group.created_by else '', 'updated_date': formats.date_format(custom_group.updated_date, "SHORT_DATETIME_FORMAT") if custom_group.updated_date else '', 'updated_by': custom_group.updated_by.username if custom_group.updated_by else '', 'permissions': permissions } return successful_response(data)
def create(self, request): assign_terminal_id = request.POST.get('assign_terminal_id', None) merchant_id = request.POST.get('merchant_id', None) team_id = request.POST.get('team_id', None) staff_id = request.POST.get('staff_id', None) name = request.POST.get('name', None) address = request.POST.get('address', None) province_id = request.POST.get('province_id', None) district_id = request.POST.get('district_id', None) wards_id = request.POST.get('wards_id', None) street = request.POST.get('street', None) description = request.POST.get('description', None) province = QrProvince.objects.filter(id=province_id).first() district = QrDistrict.objects.filter(id=district_id).first() wards = QrWards.objects.filter(id=wards_id).first() merchant = Merchant.objects.filter(id=merchant_id).first() staff = Staff.objects.filter(id=staff_id).first() code = Shop.objects.all().order_by("-id")[0].id + 1 shop = Shop(merchant=merchant, name=conditional_escape(name), code=conditional_escape(code), address=conditional_escape(address), province=province, district=district, wards=wards, street=conditional_escape(street), description=conditional_escape(description), created_by=request.user) shop.save() if staff is not None: shop.staff_create(staff.id) if int(assign_terminal_id) != 0: terminal = Terminal.objects.get(pk=assign_terminal_id) if terminal is None: return custom_response('404.006') if shop.merchant == terminal.merchant: terminal.shop = shop terminal.save() else: return custom_response('400', 'Merchant is invalid') refresh_shop_full_data() return successful_response('created')
def retrieve(self, request, pk): """ API get detail SalePromotion """ sale_promotion = SalePromotion.objects.filter(pk=pk).first() if sale_promotion is None: return custom_response(Code.PROMOTION_NOT_FOUND) data = { 'merchant': sale_promotion.get_merchant(), 'terminal': sale_promotion.get_terminal(), 'shop': sale_promotion.get_shop(), 'staff': sale_promotion.get_staff(), 'title': sale_promotion.get_title(), 'contact_person': sale_promotion.contact_person, 'contact_phone_number': sale_promotion.contact_phone_number, 'contact_email': sale_promotion.contact_email, 'tentcard_ctkm': sale_promotion.tentcard_ctkm, 'wobbler_ctkm': sale_promotion.wobbler_ctkm, 'status': sale_promotion.get_status(), 'image': sale_promotion.image if sale_promotion.image else '', 'sub_image': sale_promotion.sub_image if sale_promotion.sub_image else '', 'created_date': formats.date_format(sale_promotion.created_date, "SHORT_DATETIME_FORMAT") if sale_promotion.created_date else '', 'updated_date': formats.date_format(sale_promotion.updated_date, "SHORT_DATETIME_FORMAT") if sale_promotion.updated_date else '' } return successful_response(data)
def get_proportion_kpi_team(request): """ API danh sách tỷ trọng KPI Team \n """ data = [] areas = ProportionKpiTeam.objects.values('area', 'area__name').distinct() for item in areas: area_item = ProportionKpiTeam.objects.filter(area=item['area']).values( 'type', 'leader_coefficient').all() result = [{ 'type': q['type'], 'type_name': ProportionKpiTeamType.CHOICES[q['type']][1], 'leader_coefficient': q['leader_coefficient'] } for q in area_item] data.append({item['area__name']: result}) return successful_response(data)
def export(request): """ API export data Shop \n Parameters for this api : Có thể bỏ trống hoặc không gửi lên - code -- text - merchant_id -- number - team_id -- number - staff_id -- number - area_id -- number - province_id -- number - district_id -- number - ward_id -- number - status -- number in {0, 1, 2, 3, 4, 5, 6} = {Shop không có thông tin đường phố, Shop đã hủy or không có Terminal, Shop chưa được gán Sale, Shop phát sinh 1 GD kỳ này, Shop phát sinh 2 GD kỳ này, Shop phát sinh trên 3 GD kỳ này, Shop không phát sinh GD} - from_date -- dd/mm/yyyy - to_date -- dd/mm/yyyy """ file_path = render_excel(request) return successful_response(file_path)
def list_provinces(request): """ API get list Province to select \n Parameters for this api : Có thể bỏ trống hoặc không gửi lên - area_id -- interger - code -- text """ queryset = QrProvince.objects.values('id', 'province_code', 'province_name') # if request.user.is_superuser is False: # provinces = get_provinces_viewable_queryset(request.user) # queryset = queryset.filter(pk__in=provinces) area_id = request.GET.get('area_id', None) code = request.GET.get('code', None) if area_id is not None and area_id != '': if area_id.isdigit(): province_codes = [] area = Area.objects.get(pk=int(area_id)) provinces = area.get_provinces() for item in provinces: province_codes.append(item.province_code) queryset = queryset.filter(province_code__in=province_codes) if code is not None and code != '': code = unidecode(format_string(code)) queryset = queryset.filter( Q(province_name__unaccent__icontains=code) | Q(province_code__icontains=code)) queryset = queryset.order_by('province_name')[0:settings.PAGINATE_BY] data = [{ 'id': province['id'], 'code': province['province_code'], 'name': province['province_name'] } for province in queryset] return successful_response(data)
def list_promotion_shops_for_search(request): """ API để search full text search không dấu các shop dựa trên địa chỉ, shop_code hoặc merchant brand, param là name """ name = request.GET.get('name', None) user_info = request.user queryset = get_promotion_shops_viewable_queryset(user_info) if name is not None and name != '': name = format_string(name) querysetABS = queryset.filter( Q(code__icontains=name) | Q(merchant__merchant_brand__icontains=name) | Q(address__icontains=name))[:10] lengQuerysetABS = len(querysetABS) if lengQuerysetABS < 10: name_en = unidecode(name).lower() search_query = SearchQuery(name_en) querysetFTS = queryset.annotate(rank=SearchRank( F('document'), search_query)).order_by('-rank').exclude( pk__in=querysetABS)[:(10 - lengQuerysetABS)] else: querysetFTS = [] else: querysetABS = queryset[:10] querysetFTS = [] data = [] for shop in itertools.chain(querysetABS, querysetFTS): code = shop.code if shop.code is not None else 'N/A' address = shop.address if shop.address is not None else 'N/A' merchant_brand = shop.merchant.merchant_brand if shop.merchant.merchant_brand is not None else 'N/A' data.append({ 'id': shop.id, 'shop_info': code + ' - ' + merchant_brand + ' - ' + address }) return successful_response(data)
def export(request): """ API export data Terminal \n Parameters for this api : Có thể bỏ trống hoặc không gửi lên - shop_id -- text - terminal_text -- text - merchant_id -- number - staff_id -- number - team_id -- number - area_id -- number - province_code -- text - district_code -- text - ward_code -- text - status -- number in {-1,1,2,3,4,5,6} - from_date -- dd/mm/yyyy - to_date -- dd/mm/yyyy """ file_path = render_excel(request) return successful_response(file_path)
def retrieve(self, request, pk): """ API get detail Area """ try: area = Area.objects.filter(pk=pk).first() if area is None: return custom_response(Code.AREA_NOT_FOUND) province_lists, proportion_kpi_lists = [], [] province_code_lists = area.provinces.split(',') for item in QrProvince.objects.filter( province_code__in=province_code_lists).values( 'province_code', 'province_name'): province_lists.append({ 'province_code': item['province_code'], 'province_name': item['province_name'], }) for proportion_kpi in area.proportion_kpi.all().values( 'type', 'leader_coefficient'): proportion_kpi_lists.append({ 'type': proportion_kpi['type'], 'leader_coefficient': proportion_kpi['leader_coefficient'], }) data = { 'name': area.name, 'code': area.code, 'proportion_kpi_s73': area.proportion_kpi_s73, 'provinces': province_lists, 'proportion_kpi_team': proportion_kpi_lists } return successful_response(data) except Exception as e: logging.error('Get detail area exception: %s', e) return custom_response(Code.INTERNAL_SERVER_ERROR)
def list_groups(request): """ API get list Groups to select \n Parameters for this api : Có thể bỏ trống hoặc không gửi lên - name -- text """ queryset = CustomGroup.objects.all() name = request.GET.get('name', None) if name is not None and name != '': queryset = queryset.filter(name__icontains=name) queryset = queryset.order_by('name')[0:settings.PAGINATE_BY] data = [{ 'id': custom_group.id, 'name': custom_group.name } for custom_group in queryset] return successful_response(data)
def count_terminal_30_days_before(request): all_terminal = request.GET.get('all_terminal', None) if all_terminal is not None and all_terminal != '': terminal_count = Terminal.objects.filter(~Q(status=-1) & ~Q(register_vnpayment=1)).count() else: terminal_count = Terminal.objects.filter(Q(status=1) & ~Q(register_vnpayment=1)).count() with connection.cursor() as cursor: cursor.execute(''' select count(*), date(created_date) from terminal where created_date > current_date - interval '30 days' and register_vnpayment <> 1 and status <> -1 group by date(created_date) order by date(created_date) asc ''') columns = [col[0] for col in cursor.description] data_cursor = [ dict(zip(columns, row)) for row in cursor.fetchall() ] data_date = [] data_value = [] yesterday = 0 for item in data_cursor: if str(item['date']) == str((date.today() - timedelta(days=1)).strftime("%Y-%m-%d")): yesterday = item['count'] data_date.append(str(item['date'].strftime("%d/%m/%Y"))) data_value.append(item['count']) return successful_response({ 'data': { 'data_date': data_date, 'data_value': data_value }, 'yesterday': yesterday, 'terminal_count': terminal_count })