コード例 #1
0
ファイル: models.py プロジェクト: luckychelsea/dji_mkt
    def pick_tariff(self, tariff, author, comment=None, deadline=None) -> None:
        """
        Trying to buy a service if enough money.
        :param tariff: instance of tariff_app.models.Tariff.
        :param author: Instance of accounts_app.models.UserProfile.
        Who connected this service. May be None if author is a system.
        :param comment: Optional text for logging this pay.
        :param deadline: Instance of datetime.datetime. Date when service is
        expired.
        :return: Nothing
        """
        if not isinstance(tariff, Tariff):
            raise TypeError

        amount = round(tariff.amount, 2)

        if tariff.is_admin and author is not None:
            if not author.is_staff:
                raise LogicError(
                    _('User that is no staff can not buy admin services')
                )

        if self.current_tariff is not None:
            if self.current_tariff.tariff == tariff:
                # if service already connected
                raise LogicError(_('That service already activated'))
            else:
                # if service is present then speak about it
                raise LogicError(_('Service already activated'))

        # if not enough money
        if self.ballance < amount:
            raise LogicError(_('%s not enough money for service %s') % (
                self.username, tariff.title
            ))

        with transaction.atomic():
            new_abtar = AbonTariff.objects.create(
                deadline=deadline, tariff=tariff
            )
            self.current_tariff = new_abtar
            if self.last_connected_tariff != tariff:
                self.last_connected_tariff = tariff

            # charge for the service
            self.ballance -= amount

            self.save(update_fields=(
                'ballance',
                'current_tariff',
                'last_connected_tariff'
            ))

            # make log about it
            AbonLog.objects.create(
                abon=self, amount=-tariff.amount,
                author=author if isinstance(author, UserProfile) else None,
                comment=comment or _('Buy service default log')
            )
コード例 #2
0
 def attach_ip_addr(self, ip, strict=False):
     """
     Attach ip address to account
     :param ip: Instance of str or ip_address
     :param strict: If strict is True then ip not replaced quietly
     :return: None
     """
     if strict and self.ip_address:
         raise LogicError('Ip address already exists')
     self.ip_address = ip
     self.save(update_fields=('ip_address', ))
コード例 #3
0
def debt_buy(request, d_id):
    debt = get_object_or_404(InvoiceForPayment, id=d_id)
    abon = request.user
    if request.method == 'POST':
        try:
            sure = request.POST.get('sure')
            if sure != 'on':
                raise LogicError(
                    _("Are you not sure that you want buy the service?"))
            if abon.ballance < debt.amount:
                raise LogicError(_('Your account have not enough money'))

            amount = -debt.amount
            abon.add_ballance(
                None,
                amount,
                comment=gettext('%(username)s paid the debt %(amount).2f') % {
                    'username': abon.get_full_name(),
                    'amount': amount
                })
            abon.save(update_fields=('ballance', ))
            debt.set_ok()
            debt.save(update_fields=('status', 'date_pay'))
            return redirect('client_side:debts')
        except LogicError as e:
            messages.error(request, e)
        except NasFailedResult as e:
            messages.error(request, e)
        except NasNetworkError as e:
            messages.error(request, e)
    return render(
        request, 'clientsideapp/debt_buy.html', {
            'debt': debt,
            'amount': debt.amount,
            'ballance_after': abon.ballance - debt.amount
        })
コード例 #4
0
 def __init__(self, *args, **kwargs):
     super().__init__(*args, **kwargs)
     instance = getattr(self, 'instance')
     if instance:
         if instance.group:
             self.fields['networks'].queryset = NetworkModel.objects.filter(
                 groups=instance.group)
     if not self.initial.get('ip_address'):
         if not instance:
             raise LogicError(_('Subnet has not attached to current group'))
         if not instance.nas:
             raise LogicError(_('Please pick NAS for consumer'))
         for net in NetworkModel.objects.filter(
                 groups=instance.group).iterator():
             ips = (ip.ip_address
                    for ip in models.Abon.objects.filter_ip_address(
                        group_ids=tuple(
                            n.pk for n in net.groups.iterator()),
                        nas_id=int(instance.nas_id)).iterator())
             free_ip = net.get_free_ip(ips)
             if free_ip is None:
                 continue
             self.initial['ip_address'] = str(free_ip)
             break
コード例 #5
0
 def nas_remove_self(self):
     """
     Will remove this user to network access server
     :return:
     """
     if self.nas is None:
         raise LogicError(_('gateway required'))
     try:
         agent_abon = self.build_agent_struct()
         if agent_abon is not None:
             mngr = self.nas.get_nas_manager()
             mngr.remove_user(agent_abon)
     except (NasFailedResult, NasNetworkError, ConnectionResetError) as e:
         print('ERROR:', e)
         return e
     except LogicError:
         pass
コード例 #6
0
 def nas_sync_self(self) -> Optional[Exception]:
     """
     Synchronize user with gateway
     :return:
     """
     if self.nas is None:
         raise LogicError(_('gateway required'))
     try:
         agent_abon = self.build_agent_struct()
         if agent_abon is not None:
             mngr = self.nas.get_nas_manager()
             mngr.update_user(agent_abon)
     except (NasFailedResult, NasNetworkError, ConnectionResetError) as e:
         print('ERROR:', e)
         return e
     except LogicError:
         pass
コード例 #7
0
 def __init__(self, *args, **kwargs):
     super().__init__(*args, **kwargs)
     instance = getattr(self, 'instance')
     if instance:
         if instance.group:
             self.fields['networks'].queryset = NetworkModel.objects.filter(
                 groups=instance.group)
     if not self.initial['ip_address']:
         if instance:
             net = NetworkModel.objects.filter(
                 groups=instance.group).first()
             if net is not None:
                 ips = (ip.ip_address for ip in models.Abon.objects.filter(
                     group__in=net.groups.all(), nas=instance.nas).order_by(
                         'ip_address').only('ip_address').iterator())
                 free_ip = net.get_free_ip(ips)
                 self.initial['ip_address'] = free_ip
         else:
             raise LogicError(_('Subnet has not attached to current group'))