def get_queryset(self):

        queryset = Team.objects.all()

        if self.request.user.is_superuser is False:
            teams = get_teams_viewable_queryset(self.request.user)
            queryset = queryset.filter(pk__in=teams)

        name = self.request.query_params.get('name', None)
        code = self.request.query_params.get('code', None)
        from_date = self.request.query_params.get('from_date', None)
        to_date = self.request.query_params.get('to_date', None)

        if name is not None and name != '':
            name = format_string(name)
            queryset = queryset.filter(name__icontains=name)
        if code is not None and code != '':
            code = format_string(code)
            queryset = queryset.filter(code__icontains=code)
        if from_date is not None and from_date != '':
            queryset = queryset.filter(created_date__gte=datetime.strptime(
                from_date, '%d/%m/%Y').strftime('%Y-%m-%d %H:%M:%S'))
        if to_date is not None and to_date != '':
            queryset = queryset.filter(created_date__lte=(
                datetime.strptime(to_date, '%d/%m/%Y').strftime('%Y-%m-%d') +
                ' 23:59:59'))

        return queryset
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)
Exemple #3
0
def get_queryset_pos365_list(request):
    pos365_obj = Pos365

    queryset = pos365_obj.objects.filter(
        Q(staff__in=get_staffs_viewable_queryset(request.user))
        | Q(contract_team__in=get_teams_viewable_queryset(request.user)))

    code = request.query_params.get('code', None)
    staff_id = request.query_params.get('staff_id', None)
    contract_duration = request.query_params.get('contract_duration', None)
    province_id = request.query_params.get('province_id', None)
    from_date = request.query_params.get('from_date', None)
    to_date = request.query_params.get('to_date', None)

    if code is not None and code != '':
        code = format_string(code)
        queryset = queryset.filter(code__icontains=code)
    if staff_id is not None and staff_id != '':
        queryset = queryset.filter(staff_id=staff_id)
    if contract_duration is not None and contract_duration != '':
        contract_duration = int(contract_duration)
        queryset = queryset.filter(contract_duration=contract_duration)
    if province_id is not None and province_id != '':
        queryset = queryset.filter(customer_province=province_id)
    if from_date is not None and from_date != '':
        queryset = queryset.filter(
            contract_start_date__gte=dt_datetime.strptime(
                from_date, '%d/%m/%Y').strftime('%Y-%m-%d %H:%M:%S'))
    if to_date is not None and to_date != '':
        queryset = queryset.filter(contract_start_date__lte=(
            dt_datetime.strptime(to_date, '%d/%m/%Y').strftime('%Y-%m-%d') +
            ' 23:59:59'))
    return queryset
    def get_queryset(self):
        queryset = Area.objects.all()

        code = self.request.query_params.get('code', None)
        province = self.request.query_params.get('province', None)

        if code is not None and code != '':
            code = format_string(code)
            queryset = queryset.filter(
                Q(name__icontains=code) | Q(code__icontains=code))
        if province is not None and province != '':
            province = format_string(province)
            province = QrProvince.objects.filter(
                province_code=province).first()
            queryset = queryset.filter(provinces__icontains=province)

        return queryset
Exemple #5
0
def get_queryset_merchant_list(request):
    queryset = Merchant.objects.all()

    if request.user.is_superuser is False:
        shops = get_shops_viewable_queryset(request.user)
        queryset = queryset.filter(pk__in=shops.values('merchant'))

    merchant_text = request.query_params.get('merchant_text', None)
    area_id = request.query_params.get('area_id', None)
    province_id = request.query_params.get('province_id', None)
    status = request.query_params.get('status', None)
    from_date = request.query_params.get('from_date', None)
    to_date = request.query_params.get('to_date', None)

    if merchant_text is not None and merchant_text != '':
        merchant_text = format_string(merchant_text)
        queryset = queryset.filter(
            Q(merchant_code__icontains=merchant_text)
            | Q(merchant_name__icontains=merchant_text)
            | Q(merchant_brand__icontains=merchant_text))
    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 province_id is not None and province_id != '':
        if province_id.isdigit():
            province = QrProvince.objects.get(pk=int(province_id))
            queryset = queryset.filter(province_code=province.province_code)
    if status is not None and status != '':
        queryset = queryset.filter(status=status)
    if from_date is not None and from_date != '':
        queryset = queryset.filter(created_date__gte=datetime.strptime(
            from_date, '%d/%m/%Y').strftime('%Y-%m-%d %H:%M:%S'))
    if to_date is not None and to_date != '':
        queryset = queryset.filter(created_date__lte=(
            datetime.strptime(to_date, '%d/%m/%Y').strftime('%Y-%m-%d') +
            ' 23:59:59'))

    return queryset
Exemple #6
0
    def get_queryset(self):

        queryset = Staff.objects.all()

        if self.request.user.is_superuser is False:
            staffs = get_staffs_viewable_queryset(self.request.user)
            queryset = queryset.filter(pk__in=staffs)

        staff_code = self.request.query_params.get('staff_code', None)
        team_id = self.request.query_params.get('team_id', None)
        role = self.request.query_params.get('role', None)
        status = self.request.query_params.get('status', None)
        from_date = self.request.query_params.get('from_date', None)
        to_date = self.request.query_params.get('to_date', None)

        if staff_code is not None and staff_code != '':
            staff_code = format_string(staff_code)
            queryset = queryset.filter(
                Q(staff_code__icontains=staff_code)
                | Q(full_name__icontains=staff_code)
                | Q(email__icontains=staff_code))
        if team_id is not None and team_id != '':
            if team_id == '0':
                queryset = queryset.filter(team__isnull=True)
            else:
                queryset = queryset.filter(team_id=team_id)
        if role is not None and role != '':
            if role.isdigit():
                if int(role) == 2:
                    queryset = queryset.filter(Q(role=int(role)) | Q(role=0))
                else:
                    queryset = queryset.filter(role=int(role))
        if status is not None and status != '':
            queryset = queryset.filter(status=(1 if status == '1' else -1))
        if from_date is not None and from_date != '':
            queryset = queryset.filter(created_date__gte=datetime.strptime(
                from_date, '%d/%m/%Y').strftime('%Y-%m-%d %H:%M:%S'))
        if to_date is not None and to_date != '':
            queryset = queryset.filter(created_date__lte=(
                datetime.strptime(to_date, '%d/%m/%Y').strftime('%Y-%m-%d') +
                ' 23:59:59'))

        return queryset
Exemple #7
0
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 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 create(self, request):
        """
            API create team \n
            Request body for this api : Không được bỏ trống \n
                {
                    "code": "DN1",
                    "name": "Team Da Nang",
                    "type": 2, (type in {0,1,2} )
                    "description": "description",
                    "area_id": 1,
                    "staffs": [
                        {
                            "id": 11732,
                            "role": "TEAM_STAFF"
                        },
                        {
                            "id": 351,
                            "role": "TEAM_MANAGEMENT"
                        }
                    ]
                }
        """
        try:
            body = json.loads(request.body)

            name = body.get('name')
            code = body.get('code')
            type = body.get('type')
            area_id = body.get('area_id')
            description = body.get('description')
            staffs = body.get('staffs')

            if staffs is not None and staffs != '' and not isinstance(
                    staffs, list):
                return custom_response(Code.INVALID_BODY, 'staffs Invalid')

            if type is not None and type != '':
                if not (isinstance(type, int) and 0 <= type <= 2):
                    return custom_response(Code.INVALID_BODY, 'type Invalid')
            else:
                type = 0

            if name is None or name == '' or code is None or code == '':
                return custom_response(Code.INVALID_BODY,
                                       'name or code Invalid')

            name = format_string(name)
            code = format_string(code)

            if Team.objects.filter(
                    Q(name__iexact=name) | Q(code__iexact=code)):
                return custom_response(Code.BAD_REQUEST,
                                       'name or code be used by other Team')

            if not isinstance(area_id, int):
                return custom_response(Code.INVALID_BODY, 'area_id not valid')
            area = Area.objects.filter(pk=area_id).first()
            if area is None:
                return custom_response(Code.AREA_NOT_FOUND)

            # validate staff_list
            staff_ids = []
            team_lead_id = None
            had_leader = False
            if staffs is not None and staffs != '':
                for staff in staffs:
                    if not isinstance(staff['id'], int):
                        return custom_response(Code.INVALID_BODY,
                                               'staff_id Invalid')
                    staff_ids.append(staff['id'])
                    if staff['role'] == StaffTeamRoleType.CHOICES[
                            StaffTeamRoleType.TEAM_MANAGEMENT][1]:
                        if had_leader:
                            return custom_response(
                                Code.INVALID_BODY,
                                'Team chỉ được phép có 1 leader')
                        had_leader = True
                        team_lead_id = staff['id']
                    elif staff['role'] != StaffTeamRoleType.CHOICES[
                            StaffTeamRoleType.TEAM_STAFF][1]:
                        return custom_response(Code.INVALID_BODY,
                                               'staff_role Invalid')

                if staff_ids:
                    if len(staff_ids) != Staff.objects.filter(
                            pk__in=staff_ids).count():
                        return custom_response(Code.STAFF_NOT_FOUND)

                staff_have_teams = Staff.objects.filter(pk__in=staff_ids,
                                                        team__isnull=False)

                if staff_have_teams:
                    staff_emails = ''
                    for staff in staff_have_teams:
                        staff_emails += staff.email + ', '
                    staff_emails = staff_emails[:-2]
                    return custom_response(
                        Code.BAD_REQUEST, 'Các nhân viên: ' + staff_emails +
                        ' đang thuộc team khác')

            team = Team(code=code.upper(),
                        name=name,
                        type=type,
                        area=area,
                        description=description,
                        created_by=request.user,
                        updated_by=request.user)
            team.save(user=request.user)

            if staffs is not None and staffs != '':
                role_staff = StaffTeamRoleType.TEAM_STAFF
                Staff.objects.filter(pk__in=staff_ids).exclude(
                    pk=team_lead_id).update(team=team, role=role_staff)
                if team_lead_id in staff_ids:
                    staff_ids.remove(team_lead_id)
                self.create_staff_log(staff_ids=staff_ids,
                                      team=team,
                                      type=StaffLogType.JOIN_TEAM,
                                      role=role_staff,
                                      description='Create new team: add staff')
                update_role_for_staff(staff_ids, ROLE_SALE)

                if team_lead_id is not None:
                    role_leader = StaffTeamRoleType.TEAM_MANAGEMENT
                    staff = Staff.objects.get(pk=team_lead_id)
                    staff.team = team
                    staff.role = role_leader
                    staff.save(staff_id=staff.id,
                               team_id=team.id,
                               team_code=team.code,
                               role=role_leader,
                               log_type=StaffLogType.JOIN_TEAM,
                               description='Create new team: add management',
                               user=request.user)
                    update_role_for_staff([team_lead_id], ROLE_SALE_LEADER)

            return successful_response(team.id)

        except Exception as e:
            logging.error('Create team exception: %s', e)
            return custom_response(Code.INTERNAL_SERVER_ERROR)
    def update(self, request, pk):
        """
            API update Team \n
            Request body for this api : Không được bỏ trống \n
                {
                    "name": "team name",
                    "type": 2, (type in {0,1,2} )
                    "description": "description",
                    "area_id": 1,
                    "staffs": [
                        {
                            "id": 11732,
                            "role": "TEAM_STAFF"
                        },
                        {
                            "id": 351,
                            "role": "TEAM_MANAGEMENT"
                        }
                    ]
                }
        """
        try:
            team = Team.objects.filter(pk=pk).first()
            if team is None:
                return custom_response(Code.TEAM_NOT_FOUND)
            body = json.loads(request.body)

            name = body.get('name')
            type = body.get('type')
            description = body.get('description')
            staffs = body.get('staffs')
            area_id = body.get('area_id')

            if staffs is not None and staffs != '':
                if not isinstance(staffs, list):
                    return custom_response(Code.INVALID_BODY, 'staffs Invalid')
            else:
                staffs = []

            if name is None or name == '':
                return custom_response(Code.INVALID_BODY, 'name Invalid')

            if type is None and type == '' or not (isinstance(type, int)
                                                   and 0 <= type <= 2):
                return custom_response(Code.INVALID_BODY, 'type Invalid')

            name = format_string(name)

            if Team.objects.filter(name__iexact=name).exclude(pk=pk):
                return custom_response(Code.BAD_REQUEST,
                                       'name being used by other Team')

            area = None
            if area_id is not None and area_id != '':
                if not isinstance(area_id, int):
                    return custom_response(Code.INVALID_BODY,
                                           'area_id not valid')
                area = Area.objects.filter(pk=area_id).first()
                if area is None:
                    return custom_response(Code.AREA_NOT_FOUND)

            role_staff = StaffTeamRoleType.TEAM_STAFF
            role_leader = StaffTeamRoleType.TEAM_MANAGEMENT

            staff_ids = []
            had_leader = False
            new_staff_ids = []
            new_leader_id = None
            update_to_staff_id = None
            update_to_leader_id = None

            # Validate staff lists
            for st in staffs:
                is_leader = False
                if not isinstance(st['id'], int):
                    return custom_response(Code.INVALID_BODY,
                                           'staff_id Invalid')

                staff_ids.append(st['id'])

                if st['role'] == StaffTeamRoleType.CHOICES[
                        StaffTeamRoleType.TEAM_MANAGEMENT][1]:
                    if had_leader:
                        return custom_response(
                            Code.INVALID_BODY,
                            'Team chỉ được phép có 1 leader')
                    had_leader = True
                    is_leader = True
                elif st['role'] != StaffTeamRoleType.CHOICES[
                        StaffTeamRoleType.TEAM_STAFF][1]:
                    return custom_response(Code.INVALID_BODY,
                                           'staff_role Invalid')

                staff = Staff.objects.filter(pk=st['id']).first()
                if staff is None:
                    return custom_response(
                        Code.STAFF_NOT_FOUND,
                        'staff_id ' + str(st['id']) + ' not found')
                if staff.team is None:
                    if is_leader:
                        new_leader_id = st['id']
                    else:
                        new_staff_ids.append(st['id'])
                elif staff.team == team:
                    if StaffTeamRoleType.CHOICES[staff.role][1] != st['role']:
                        if is_leader:
                            update_to_leader_id = st['id']
                        else:
                            update_to_staff_id = st['id']
                else:
                    return custom_response(
                        Code.BAD_REQUEST,
                        'Nhân viên ' + staff.email + ' đang thuộc team khác')

            staffs_remove = Staff.objects.filter(team=team).exclude(
                pk__in=staff_ids)
            remove_ids = []
            if staffs_remove:
                for id in staffs_remove.values('id'):
                    remove_ids.append(id['id'])

            with transaction.atomic():
                if staffs_remove:
                    StaffCare.objects.filter(staff__in=staffs_remove).delete()
                    StaffCareLog.objects.filter(
                        staff__in=staffs_remove, is_caring=True).update(
                            is_caring=False,
                            updated_by=request.user,
                            updated_date=datetime.now(),
                        )

                    staffs_remove.update(
                        team=None, role=StaffTeamRoleType.FREELANCE_STAFF)
                    self.create_staff_log(
                        staff_ids=remove_ids,
                        team=team,
                        type=StaffLogType.OUT_TEAM,
                        role=StaffTeamRoleType.FREELANCE_STAFF,
                        description='Update team: remove staff from team')
                    update_role_for_staff(remove_ids, ROLE_SALE)

                if new_staff_ids:
                    Staff.objects.filter(pk__in=new_staff_ids).update(
                        team=team, role=role_staff)
                    self.create_staff_log(
                        staff_ids=new_staff_ids,
                        team=team,
                        type=StaffLogType.JOIN_TEAM,
                        role=role_staff,
                        description='Update team: add new staff')
                    update_role_for_staff(new_staff_ids, ROLE_SALE)

                if new_leader_id is not None:
                    staff = Staff.objects.get(pk=new_leader_id)
                    staff.team = team
                    staff.role = role_leader
                    staff.save(staff_id=new_leader_id,
                               team_id=team.id,
                               team_code=team.code,
                               role=role_leader,
                               log_type=StaffLogType.JOIN_TEAM,
                               description='Update team: add new management',
                               user=request.user)
                    update_role_for_staff([new_leader_id], ROLE_SALE_LEADER)

                if update_to_staff_id is not None:
                    staff = Staff.objects.get(pk=update_to_staff_id)
                    staff.role = role_staff
                    staff.save(staff_id=update_to_staff_id,
                               team_id=team.id,
                               team_code=team.code,
                               role=role_staff,
                               log_type=StaffLogType.UPDATE_ROLE,
                               description='Update team: demote to staff',
                               user=request.user)
                    update_role_for_staff([update_to_staff_id], ROLE_SALE)

                if update_to_leader_id is not None:
                    staff = Staff.objects.get(pk=update_to_leader_id)
                    staff.role = role_leader
                    staff.save(
                        staff_id=update_to_leader_id,
                        team_id=team.id,
                        team_code=team.code,
                        role=role_leader,
                        log_type=StaffLogType.UPDATE_ROLE,
                        description='Update team: promote to management',
                        user=request.user)
                    update_role_for_staff([update_to_leader_id],
                                          ROLE_SALE_LEADER)

                team.name = name
                team.type = type
                team.description = description
                team.updated_by = request.user
                if area is not None:
                    team.area = area
                team.save(user=request.user, action="update")

            return successful_response()
        except Exception as e:
            logging.error('Update team exception: %s', e)
            return custom_response(Code.INTERNAL_SERVER_ERROR)
Exemple #11
0
def get_queryset_shop_list(request, export_data=False):
    status = request.query_params.get('status', None)

    shop_obj = Shop
    if not export_data:
        shop_obj = ShopFullData

    if status is not None and status != '':
        if status == '0':
            queryset = shop_obj.objects.shop_active().filter(
                Q(street__isnull=True) | Q(street=''))
        elif status == '1':
            queryset = shop_obj.objects.shop_disable()
        elif status == '2':
            shop_caring_lists = StaffCare.objects.filter(
                type=StaffCareType.STAFF_SHOP).values('shop')
            queryset = shop_obj.objects.shop_active().filter(~Q(
                pk__in=shop_caring_lists))
        else:
            if status == '3':
                shop_lists = ShopCube.objects.number_of_tran_this_week(
                    value=1).values('shop_id')
            elif status == '4':
                shop_lists = ShopCube.objects.number_of_tran_this_week(
                    value=2).values('shop_id')
            elif status == '5':
                shop_lists = ShopCube.objects.number_of_tran_this_week(
                    value=3).values('shop_id')
            else:
                shop_lists = ShopCube.objects.number_of_tran_this_week(
                    value=0).values('shop_id')
            queryset = shop_obj.objects.shop_active().filter(pk__in=shop_lists)
    else:
        queryset = shop_obj.objects.shop_active()

    if request.user.is_superuser is False:
        if request.user.is_area_manager or request.user.is_sale_admin:
            if request.user.is_manager_outside_vnpay:
                shops = get_shops_viewable_queryset(request.user)
                queryset = queryset.filter(pk__in=shops)
            else:
                provinces_viewable = get_provinces_viewable_queryset(
                    request.user)
                cross_assign_status = request.query_params.get(
                    'cross_assign_status', None)
                if cross_assign_status is not None and cross_assign_status != '':
                    if cross_assign_status == '0':
                        staff_viewable = get_staffs_viewable_queryset(
                            request.user)
                        shop_ids = StaffCare.objects.filter(staff__in=staff_viewable, type=StaffCareType.STAFF_SHOP) \
                            .values('shop_id')
                        queryset = queryset.filter(pk__in=shop_ids).exclude(
                            province__in=provinces_viewable)
                    if cross_assign_status == '1':
                        staff_viewable = get_staffs_viewable_queryset(
                            request.user)
                        shop_ids = StaffCare.objects.filter(type=StaffCareType.STAFF_SHOP) \
                            .exclude(staff__in=staff_viewable).values('shop_id')
                        queryset = queryset.filter(
                            pk__in=shop_ids, province__in=provinces_viewable)
                    if cross_assign_status == '2':
                        staff_viewable = get_staffs_viewable_queryset(
                            request.user)
                        shop_id_can_view = StaffCare.objects.filter(staff__in=staff_viewable,
                                                                    type=StaffCareType.STAFF_SHOP) \
                            .values('shop_id')
                        shop_id_can_not_view = StaffCare.objects.filter(type=StaffCareType.STAFF_SHOP) \
                            .exclude(staff__in=staff_viewable).values('shop_id')
                        queryset = queryset.filter(
                            (Q(pk__in=shop_id_can_not_view)
                             & Q(province__in=provinces_viewable))
                            | (Q(pk__in=shop_id_can_view)
                               & ~Q(province__in=provinces_viewable)))
                else:
                    queryset = queryset.filter(
                        province_id__in=provinces_viewable)
        else:
            shops = get_shops_viewable_queryset(request.user)
            queryset = queryset.filter(pk__in=shops)

    code = request.query_params.get('code', None)
    merchant_id = request.query_params.get('merchant_id', None)
    team_id = request.query_params.get('team_id', None)
    staff_id = request.query_params.get('staff_id', None)
    area_id = request.query_params.get('area_id', None)
    province_id = request.query_params.get('province_id', None)
    district_id = request.query_params.get('district_id', None)
    ward_id = request.query_params.get('ward_id', None)
    from_date = request.query_params.get('from_date', None)
    to_date = request.query_params.get('to_date', None)

    if code is not None and code != '':
        code = format_string(code)
        queryset = queryset.filter(
            Q(code__icontains=code) | Q(name__icontains=code))

    if merchant_id is not None and merchant_id != '':
        queryset = queryset.filter(merchant_id=merchant_id)

    if team_id is not None and team_id != '':
        staffs = Staff.objects.filter(team=team_id)
        shop_ids = StaffCare.objects.filter(
            staff__in=staffs, type=StaffCareType.STAFF_SHOP).values('shop_id')
        queryset = queryset.filter(pk__in=shop_ids)

    if staff_id is not None and staff_id != '':
        shop_ids = StaffCare.objects.filter(
            staff=staff_id, type=StaffCareType.STAFF_SHOP).values('shop_id')
        queryset = queryset.filter(pk__in=shop_ids)

    if area_id is not None and area_id != '':
        if area_id.isdigit():
            area = Area.objects.get(pk=int(area_id))
            provinces = area.get_provinces()
            queryset = queryset.filter(province_id__in=provinces)

    if province_id is not None and province_id != '':
        queryset = queryset.filter(province_id=province_id)

    if district_id is not None and district_id != '':
        queryset = queryset.filter(district_id=district_id)

    if ward_id is not None and ward_id != '':
        queryset = queryset.filter(wards_id=ward_id)

    if from_date is not None and from_date != '':
        queryset = queryset.filter(created_date__gte=datetime.strptime(
            from_date, '%d/%m/%Y').strftime('%Y-%m-%d %H:%M:%S'))

    if to_date is not None and to_date != '':
        queryset = queryset.filter(created_date__lte=(
            datetime.strptime(to_date, '%d/%m/%Y').strftime('%Y-%m-%d') +
            ' 23:59:59'))
    return queryset.order_by('-id')
Exemple #12
0
def get_queryset_terminal_list(request):
    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:
            # Neu la SM (or SA) cua tripi, teko thi load ds shop => ds ter
            if request.user.is_manager_outside_vnpay:
                shops = get_shops_viewable_queryset(request.user)
                queryset = queryset.filter(shop__in=shops)
            # Neu la SM (or SA) cua Vnpay thi load ds provinces => ds ter
            else:
                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)

    shop_id = request.query_params.get('shop_id', None)
    terminal_text = request.query_params.get('terminal_text', None)
    area_id = request.query_params.get('area_id', None)
    merchant_id = request.query_params.get('merchant_id', None)
    staff_id = request.query_params.get('staff_id', None)
    team_id = request.query_params.get('team_id', None)
    status = request.query_params.get('status', None)
    province_code = request.query_params.get('province_code', None)
    district_code = request.query_params.get('district_code', None)
    ward_code = request.query_params.get('ward_code', None)
    from_date = request.query_params.get('from_date', None)
    to_date = request.query_params.get('to_date', None)
    assign_shop = request.query_params.get('assign_shop', None)

    if shop_id is not None and shop_id != '':
        shop_id = format_string(shop_id)
        queryset = queryset.filter(shop_id=shop_id)

    if terminal_text is not None and terminal_text != '':
        terminal_text = format_string(terminal_text)
        queryset = queryset.filter(
            Q(terminal_id__icontains=terminal_text) | Q(terminal_name__icontains=terminal_text))

    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 merchant_id is not None and merchant_id != '':
        queryset = queryset.filter(merchant_id=merchant_id)

    if staff_id is not None and staff_id != '':
        shops = StaffCare.objects.filter(staff_id=staff_id, type=StaffCareType.STAFF_SHOP).values('shop')
        queryset = queryset.filter(shop__in=shops)

    if team_id is not None and team_id != '':
        staffs = Staff.objects.filter(team_id=team_id)
        shops = StaffCare.objects.filter(staff__in=staffs, type=StaffCareType.STAFF_SHOP).values('shop')
        queryset = queryset.filter(shop__in=shops)

    if status is not None and status != '':
        queryset = queryset.filter(status=int(status))

    if province_code is not None and province_code != '':
        queryset = queryset.filter(province_code=province_code)

    if district_code is not None and district_code != '':
        queryset = queryset.filter(district_code=district_code)

    if ward_code is not None and ward_code != '':
        queryset = queryset.filter(wards_code=ward_code)

    if assign_shop is not None and assign_shop != '':
        if assign_shop == '1':
            queryset = queryset.filter(shop__isnull=False)
        else:
            queryset = queryset.filter(shop__isnull=True)

    if from_date is not None and from_date != '':
        queryset = queryset.filter(
            created_date__gte=datetime.strptime(from_date, '%d/%m/%Y').strftime('%Y-%m-%d %H:%M:%S'))

    if to_date is not None and to_date != '':
        queryset = queryset.filter(
            created_date__lte=(datetime.strptime(to_date, '%d/%m/%Y').strftime('%Y-%m-%d') + ' 23:59:59'))

    return queryset
Exemple #13
0
    def create(self, request):
        """
            API create Pos365 \n
            Request body for this api : Định dạng form-data \n
                "code": "IRNARF",
                "contract_duration": 1, (type in {0,1,2,3,4,5,6,...} )
                "contract_coefficient": 100,
                "staff_id": 1210,
                "contract_team": 1210,
                "contract_start_date": "25/01/2020" (format date in %d/%m/%Y),
                "contract_url": "https://canifa.vn",
                "contract_product_quantity": 1,
                "contract_product_series": "JX-13231; YG-14r638",
                "contract_revenue": 150000,
                "contract_note": "Đây là ghi chú mẫu",
                "contract_file": "",
                "customer_merchant": "Canifa",
                "customer_name": "Đào Hải Long",
                "customer_phone": "038123456",
                "customer_address": "36 Hoàng Cầu, Q Đống Đa, Hà Nội"
                "customer_province": 1 -- number,
        """
        try:
            data = json.loads(request.POST.get('data'))

            code = data.get('code', None)
            contract_duration = data.get('contract_duration', None)
            contract_coefficient = data.get('contract_coefficient', None)
            staff_id = data.get('staff_id', None)
            is_collaborators = data.get('is_collaborators', None)
            contract_team = data.get('contract_team', None)
            contract_url = data.get('contract_url', None)
            contract_product_quantity = data.get('contract_product_quantity',
                                                 None)
            contract_product_series = data.get('contract_product_series', None)
            contract_revenue = data.get('contract_revenue', None)
            contract_note = data.get('contract_note', None)
            contract_start_date = data.get('contract_start_date', None)
            contract_file = request.FILES[
                'contract_file'] if 'contract_file' in request.FILES else None
            customer_merchant = data.get('customer_merchant', None)
            customer_name = data.get('customer_name', None)
            customer_phone = data.get('customer_phone', None)
            customer_address = data.get('customer_address', None)
            customer_province = data.get('customer_province', None)

            if contract_duration is not None and contract_duration != '':
                if not (isinstance(contract_duration, int) or
                        (ExchangePointPos365.objects.filter(
                            pk=contract_duration).count() != 1)):
                    return custom_response(Code.INVALID_BODY,
                                           'contract_duration Invalid')

            if contract_coefficient is not None and contract_coefficient != '':
                if not (isinstance(contract_coefficient, int)
                        and 0 <= contract_coefficient <= 100):
                    return custom_response(Code.INVALID_BODY,
                                           'contract_coefficient Invalid')

            if code is None or code == '':
                return custom_response(Code.INVALID_BODY, 'code Invalid')
            code = format_string(code)

            if Pos365.objects.filter(code__iexact=code):
                return custom_response(Code.BAD_REQUEST,
                                       'code be used by other Pos365')

            if is_collaborators:
                if (not isinstance(contract_team, int)) or (
                        Team.objects.filter(pk=contract_team).count() != 1):
                    return custom_response(Code.TEAM_NOT_FOUND)
                else:
                    contract_team = Team.objects.get(pk=contract_team)
            else:
                if (not isinstance(staff_id, int)) or (
                        Staff.objects.filter(pk=staff_id).count() != 1):
                    return custom_response(Code.STAFF_NOT_FOUND)

            if not isinstance(contract_product_quantity, int):
                return custom_response(Code.BAD_REQUEST,
                                       'Số lượng sản phẩm phải số nguyên')

            if contract_file is not None:
                fs = FileSystemStorage(location=settings.FS_DOCUMENT_UPLOADS +
                                       datetime.date.today().isoformat(),
                                       base_url=settings.FS_DOCUMENT_URL +
                                       datetime.date.today().isoformat())
                file_type = os.path.splitext(contract_file.name)[1]
                filename = fs.save(
                    str(request.user.username) + str(time()) + file_type,
                    contract_file)
                uploaded_file_url = fs.url(filename)
            else:
                uploaded_file_url = None

            contract_url = format_string(contract_url)
            contract_product_quantity = int(contract_product_quantity)
            contract_product_series = format_string(contract_product_series)
            contract_note = format_string(contract_note)
            contract_start_date = dt_datetime.strptime(
                contract_start_date[:10], '%Y-%m-%d')

            customer_merchant = format_string(customer_merchant)
            customer_name = format_string(customer_name)
            customer_phone = format_string(customer_phone)
            customer_address = format_string(customer_address)
            province = QrProvince.objects.filter(
                pk=int(customer_province)).first()
            if not province:
                return custom_response(Code.BAD_REQUEST, 'Wrong Province')

            pos365 = Pos365(
                code=code,
                contract_duration=contract_duration,
                contract_coefficient=contract_coefficient,
                staff_id=staff_id,
                contract_team=contract_team,
                contract_url=contract_url,
                contract_product_quantity=contract_product_quantity,
                contract_product_series=contract_product_series,
                contract_revenue=contract_revenue,
                contract_note=contract_note,
                contract_start_date=contract_start_date,
                contract_file=uploaded_file_url,
                customer_merchant=customer_merchant,
                customer_name=customer_name,
                customer_phone=customer_phone,
                customer_address=customer_address,
                customer_province=province,
                created_by=request.user,
                updated_by=request.user)
            pos365.save()

            return successful_response(pos365.id)

        except Exception as e:
            logging.error('Create pos365 exception: %s', e)
            return custom_response(Code.INTERNAL_SERVER_ERROR)