Ejemplo n.º 1
0
def terminal_info(term_id):
    """Информация о терминале"""

    firm_terms = FirmTerm.get_list_by_firm_id(g.firm_info['id'])
    if not term_id in firm_terms:
        abort(403)

    term = Term.get_info_by_id(term_id)
    if not term:
        abort(404)

    term_access = term_id in FirmTerm.get_list_by_firm_id(
        g.firm_info['id'], False)
    term_events = TermEvent().get_by_term_id(term_id)
    alarm = AlarmStack(firm_id=g.firm_info['id'],
                       term_id=term_id).get_term_alarm()

    return render_template('term/terminal/view.html',
                           term=term,
                           events=EventType.get_dict(term.type),
                           term_event=TermEvent(),
                           term_events=term_events,
                           term_access=term_access,
                           term_types=Term().get_type_list(),
                           term_factors=Term().get_factor_list(),
                           term_auth=Term().get_auth_list(),
                           term_blacklist=Term().get_blacklist_list(),
                           alarm_stack=alarm)
Ejemplo n.º 2
0
def terminal_info(term_id):
    """Информация о терминале"""

    firm_terms = FirmTerm.get_list_by_firm_id(g.firm_info['id'])
    if not term_id in firm_terms:
        abort(403)

    term = Term.get_info_by_id(term_id)
    if not term:
        abort(404)

    term_access = term_id in FirmTerm.get_list_by_firm_id(
        g.firm_info['id'], False)
    term_events = TermEvent().get_by_term_id(term_id)
    alarm = AlarmStack(
        firm_id=g.firm_info['id'],
        term_id=term_id).get_term_alarm()

    return render_template(
        'term/terminal/view.html',
        term=term,
        events=EventType.get_dict(term.type),
        term_event=TermEvent(),
        term_events=term_events,
        term_access=term_access,
        term_types=Term().get_type_list(),
        term_factors=Term().get_factor_list(),
        term_auth=Term().get_auth_list(),
        term_blacklist=Term().get_blacklist_list(),
        alarm_stack=alarm
    )
Ejemplo n.º 3
0
def alarm_remove():
    """Удаление оповещения"""

    answer = dict(error='yes', message=u'Произошла ошибка')

    arg = get_post_arg(request, True)
    arg['firm_id'] = int(g.firm_info['id'])

    if not 'term_id' in arg or not Term.get_by_id(arg['term_id']):
        abort(404)

    term_access = arg['term_id'] in FirmTerm.get_list_by_firm_id(
        g.firm_info['id'], False)
    if not term_access:
        term_rent = FirmTerm.query.filter_by(
            term_id=arg['term_id'], child_firm_id=g.firm_info['id']).all()
        if not term_rent:
            abort(403)

    alarm_stack = AlarmStack.query.filter_by(term_id=arg['term_id'],
                                             firm_id=arg['firm_id']).first()
    if not alarm_stack:
        abort(404)

    alarm_stack.delete()
    answer['error'] = 'no'
    answer['message'] = u'Оповещение удалено'

    return jsonify(answer)
Ejemplo n.º 4
0
def alarm_remove():
    """Удаление оповещения"""

    answer = dict(error='yes', message=u'Произошла ошибка')

    arg = get_post_arg(request, True)
    arg['firm_id'] = int(g.firm_info['id'])

    if not 'term_id' in arg or not Term.get_by_id(arg['term_id']):
        abort(404)

    term_access = arg['term_id'] in FirmTerm.get_list_by_firm_id(
        g.firm_info['id'], False)
    if not term_access:
        term_rent = FirmTerm.query.filter_by(
            term_id=arg['term_id'], child_firm_id=g.firm_info['id']).all()
        if not term_rent:
            abort(403)

    alarm_stack = AlarmStack.query.filter_by(
        term_id=arg['term_id'], firm_id=arg['firm_id']).first()
    if not alarm_stack:
        abort(404)

    alarm_stack.delete()
    answer['error'] = 'no'
    answer['message'] = u'Оповещение удалено'

    return jsonify(answer)
Ejemplo n.º 5
0
    def lost_report_watcher(term_id, report_max_date):
        full_format = '%Y-%m-%d %H:%M:%S'
        short_format = '%Y-%m-%d'

        report_max_date = datetime.strptime(report_max_date, full_format)
        details = date_helper.get_date_interval(report_max_date)
        details = map(lambda row: str(row), details)

        start = datetime.strptime(details[0], full_format)
        end = datetime.strptime(details[1], full_format)
        details = {'period': {
            'start': start.strftime(short_format),
            'end': end.strftime(short_format)}}

        firms = FirmTerm.get_list_by_term_id(term_id)
        for firm in firms:
            report_stack = ReportStack.query.filter_by(
                firm_id=firm, interval=ReportStack.INTERVAL_DAY).all()
            if not report_stack:
                continue

            for row in report_stack:
                if not report_max_date < row.launch_date:
                    continue

                stack = row.copy_new_from_old()
                stack.interval = ReportStack.INTERVAL_ONCE
                stack.name = 'Lost'
                stack.details = details
                stack.save()

        return True
Ejemplo n.º 6
0
def terminal_rent_add(term_id):
    """Сдаём терминал в аренду"""

    answer = dict(error='yes', message=u'Произошла ошибка')
    arg = get_post_arg(request, True)
    error = False

    if not Term.get_by_id(term_id):
        abort(404)

    firm_terms = FirmTerm.query.filter_by(
        term_id=term_id,
        firm_id=g.firm_info['id']).all()
    if not firm_terms:
        abort(405)

    child_firm = Firm.query.filter_by(sub_domain=arg['sub_domain']).first()
    if not child_firm:
        answer['message'] = u'Фирма с таким поддоменом не найдена'
        return jsonify(answer)

    if child_firm.id == g.firm_info['id']:
        answer['message'] = u'Вы не можете сдать терминал сами себе'
        return jsonify(answer)

    parent_firm_id = False
    for firm_term in firm_terms:
        parent_firm_id = firm_term.firm_id
        if firm_term.child_firm_id == child_firm.id:
            error = True

    if error:
        answer['message'] = u'Вы уже сдаете этот терминал данной фирме'
        return jsonify(answer)

    firm_term = FirmTerm()
    firm_term.term_id = term_id
    firm_term.firm_id = parent_firm_id
    firm_term.child_firm_id = child_firm.id

    if firm_term.save():
        answer['error'] = 'no'
        answer['message'] = u'Операция выполнена'

    return jsonify(answer)
Ejemplo n.º 7
0
    def select_term_list(firm_id, **kwargs):
        date_pattern = '%H:%M %d.%m.%y'

        order = kwargs['order'] if 'order' in kwargs and kwargs[
            'order'] else 'config_date'
        order_desc = kwargs['order_desc'] if 'order_desc' in kwargs else True
        limit = kwargs['limit'] if 'limit' in kwargs else 10
        page = kwargs['page'] if 'page' in kwargs else 1

        firm_term = FirmTerm.get_list_by_firm_id(firm_id)
        g.firm_term = firm_term

        query = Term.query.filter(Term.id.in_(firm_term))

        if order:
            if order_desc:
                query = query.order_by(desc(order))
            else:
                query = query.order_by(order)

        terms = query.paginate(page, limit, False).items

        result = []
        for term in terms:
            firm_general = FirmTerm.query.filter_by(term_id=term.id).first()

            seans_date = None
            seans_alarm = 0
            if term.config_date:
                delta = date_helper.get_current_date(
                    format=False) - term.config_date

                seans_alarm = delta.total_seconds() > Term.SEANS_ALARM

                seans_date = date_helper.from_utc(term.config_date, term.tz)
                seans_date = seans_date.strftime(date_pattern)
            data = dict(
                id=term.id,
                hard_id=term.hard_id,
                name=term.name,
                firm=firm_general.firm.name,
                status=int(term.status == Term.STATUS_VALID),
                seans_date=seans_date,
                seans_alarm=int(seans_alarm),
                tz=term.tz,
            )

            result.append(data)

        value = dict(
            result=result,
            count=query.count(),
        )

        return value
Ejemplo n.º 8
0
    def select_term_list(firm_id, **kwargs):
        date_pattern = '%H:%M %d.%m.%y'

        order = kwargs['order'] if 'order' in kwargs and kwargs[
            'order'] else 'config_date'
        order_desc = kwargs['order_desc'] if 'order_desc' in kwargs else True
        limit = kwargs['limit'] if 'limit' in kwargs else 10
        page = kwargs['page'] if 'page' in kwargs else 1

        firm_term = FirmTerm.get_list_by_firm_id(firm_id)
        g.firm_term = firm_term

        query = Term.query.filter(Term.id.in_(firm_term))

        if order:
            if order_desc:
                query = query.order_by(desc(order))
            else:
                query = query.order_by(order)

        terms = query.paginate(page, limit, False).items

        result = []
        for term in terms:
            firm_general = FirmTerm.query.filter_by(term_id=term.id).first()

            seans_date = None
            seans_alarm = 0
            if term.config_date:
                delta = date_helper.get_current_date(
                    format=False) - term.config_date

                seans_alarm = delta.total_seconds() > Term.SEANS_ALARM

                seans_date = date_helper.from_utc(term.config_date, term.tz)
                seans_date = seans_date.strftime(date_pattern)
            data = dict(
                id=term.id,
                hard_id=term.hard_id,
                name=term.name,
                firm=firm_general.firm.name,
                status=int(term.status == Term.STATUS_VALID),
                seans_date=seans_date,
                seans_alarm=int(seans_alarm),
                tz=term.tz,
            )

            result.append(data)

        value = dict(
            result=result,
            count=query.count(),
        )

        return value
Ejemplo n.º 9
0
    def term_add(self, firm_id):
        result = False

        if self.save():
            firm_term = FirmTerm()
            firm_term.term_id = self.id
            firm_term.firm_id = firm_id
            firm_term.child_firm_id = firm_id
            firm_term.save()
            result = True
        return result
Ejemplo n.º 10
0
def terminal_rent_info(term_id):
    """Информация о сдачи терминала в аренду"""

    answer = dict(error='yes', message=u'Произошла ошибка')

    term = Term.get_info_by_id(term_id)
    if not term:
        abort(404)

    firm_terms = FirmTerm.get_rent(term.id, g.firm_info['id'])
    rents = [row.to_json() for row in firm_terms]

    answer['error'] = 'no'
    answer['message'] = ''
    answer['rents'] = rents
    return jsonify(answer)
Ejemplo n.º 11
0
def terminal_rent_info(term_id):
    """Информация о сдачи терминала в аренду"""

    answer = dict(error='yes', message=u'Произошла ошибка')

    term = Term.get_info_by_id(term_id)
    if not term:
        abort(404)

    firm_terms = FirmTerm.get_rent(term.id, g.firm_info['id'])
    rents = [row.to_json() for row in firm_terms]

    answer['error'] = 'no'
    answer['message'] = ''
    answer['rents'] = rents
    return jsonify(answer)
Ejemplo n.º 12
0
    def term_add(self, firm_id):
        result = False

        if self.save():
            firm_term = FirmTerm()
            firm_term.term_id = self.id
            firm_term.firm_id = firm_id
            firm_term.child_firm_id = firm_id
            firm_term.save()
            result = True
        return result
Ejemplo n.º 13
0
def terminal_event_delete(term_id, term_event_id):
    """Удаляем событие привязаное к терминалу"""

    answer = dict(error='yes', message=u'Произошла ошибка')

    firm_term = FirmTerm.get_list_by_firm_id(g.firm_info['id'])
    if term_id not in firm_term:
        abort(403)

    term_event = TermEvent.query.filter_by(
        term_id=term_id, id=term_event_id).first()

    if not term_event:
        abort(400)

    if term_event.term_event_remove(g.firm_info['id']):
        answer['error'] = 'no'
        answer['message'] = u'Событие удалено'

    return jsonify(answer)
Ejemplo n.º 14
0
def terminal_event_delete(term_id, term_event_id):
    """Удаляем событие привязаное к терминалу"""

    answer = dict(error='yes', message=u'Произошла ошибка')

    firm_term = FirmTerm.get_list_by_firm_id(g.firm_info['id'])
    if term_id not in firm_term:
        abort(403)

    term_event = TermEvent.query.filter_by(term_id=term_id,
                                           id=term_event_id).first()

    if not term_event:
        abort(400)

    if term_event.term_event_remove(g.firm_info['id']):
        answer['error'] = 'no'
        answer['message'] = u'Событие удалено'

    return jsonify(answer)
Ejemplo n.º 15
0
def alarm_save():
    """Создание нового или редактирование оповещения"""

    answer = dict(error='yes', message=u'Произошла ошибка')

    arg = get_post_arg(request, True)
    arg['interval'] = int(arg['interval'][0:2]) * \
        60 * 60 + int(arg['interval'][3:5]) * 60

    if not 'term_id' in arg:
        abort(404)

    term = Term.get_by_id(arg['term_id'])
    if not term:
        abort(404)

    firm_term = FirmTerm.get_list_by_firm_id(g.firm_info['id'])
    if term.id not in firm_term:
        abort(403)

    alarm_stack = AlarmStack.query.filter_by(
        term_id=arg['term_id'], firm_id=g.firm_info['id']).first()
    if not alarm_stack:
        alarm_stack = AlarmStack()

    arg['emails'] = AlarmStack().encode_field(arg['emails'])
    form = TermAlarmForm.from_json(arg)
    if not form.validate():
        answer['message'] = u'Форма заполнена неверно, проверьте формат полей'
        return jsonify(answer)

    form.populate_obj(alarm_stack)
    alarm_stack.firm_id = g.firm_info['id']
    if alarm_stack.save():
        answer['error'] = 'no'
        answer['message'] = u'Оповещение сохранено'

    return jsonify(answer)
Ejemplo n.º 16
0
def alarm_save():
    """Создание нового или редактирование оповещения"""

    answer = dict(error='yes', message=u'Произошла ошибка')

    arg = get_post_arg(request, True)
    arg['interval'] = int(arg['interval'][0:2]) * \
        60 * 60 + int(arg['interval'][3:5]) * 60

    if not 'term_id' in arg:
        abort(404)

    term = Term.get_by_id(arg['term_id'])
    if not term:
        abort(404)

    firm_term = FirmTerm.get_list_by_firm_id(g.firm_info['id'])
    if term.id not in firm_term:
        abort(403)

    alarm_stack = AlarmStack.query.filter_by(
        term_id=arg['term_id'], firm_id=g.firm_info['id']).first()
    if not alarm_stack:
        alarm_stack = AlarmStack()

    arg['emails'] = AlarmStack().encode_field(arg['emails'])
    form = TermAlarmForm.from_json(arg)
    if not form.validate():
        answer['message'] = u'Форма заполнена неверно, проверьте формат полей'
        return jsonify(answer)

    form.populate_obj(alarm_stack)
    alarm_stack.firm_id = g.firm_info['id']
    if alarm_stack.save():
        answer['error'] = 'no'
        answer['message'] = u'Оповещение сохранено'

    return jsonify(answer)
Ejemplo n.º 17
0
def terminal_rent_add(term_id):
    """Сдаём терминал в аренду"""

    answer = dict(error='yes', message=u'Произошла ошибка')
    arg = get_post_arg(request, True)
    error = False

    if not Term.get_by_id(term_id):
        abort(404)

    firm_terms = FirmTerm.query.filter_by(term_id=term_id,
                                          firm_id=g.firm_info['id']).all()
    if not firm_terms:
        abort(405)

    child_firm = Firm.query.filter_by(sub_domain=arg['sub_domain']).first()
    if not child_firm:
        answer['message'] = u'Фирма с таким поддоменом не найдена'
        return jsonify(answer)

    if child_firm.id == g.firm_info['id']:
        answer['message'] = u'Вы не можете сдать терминал сами себе'
        return jsonify(answer)

    parent_firm_id = False
    for firm_term in firm_terms:
        parent_firm_id = firm_term.firm_id
        if firm_term.child_firm_id == child_firm.id:
            error = True

    if error:
        answer['message'] = u'Вы уже сдаете этот терминал данной фирме'
        return jsonify(answer)

    firm_term = FirmTerm()
    firm_term.term_id = term_id
    firm_term.firm_id = parent_firm_id
    firm_term.child_firm_id = child_firm.id

    if firm_term.save():
        answer['error'] = 'no'
        answer['message'] = u'Операция выполнена'

    return jsonify(answer)
Ejemplo n.º 18
0
 def get_by_firm_id(self, firm_id):
     firm_term = FirmTerm.get_list_by_firm_id(firm_id)
     return self.query.filter(
         TermEvent.term_id.in_(
             firm_term)).all()
Ejemplo n.º 19
0
 def get_by_firm_id(self, firm_id):
     firm_term = FirmTerm.get_list_by_firm_id(firm_id)
     return self.query.filter(TermEvent.term_id.in_(firm_term)).all()
Ejemplo n.º 20
0
    def account_generate(firm_id, search_date, send=True):
        log = logging.getLogger('task')

        firm = Firm.query.get(firm_id)
        if not firm:
            log.error('Not found firm with id %s' % firm_id)
            return False

        firm_term = FirmTerm.get_list_by_firm_id(firm.id, False)
        leased_term = FirmTerm.get_list_by_firm_id(firm.id, True)
        comission_terms = []

        for term_id in (firm_term | leased_term):
            term = Term.query.get(term_id)
            if not term.has_comission:
                continue
            comission_terms.append(term.id)

        interval_date = search_date - timedelta(days=20)
        interval = date_helper.get_date_interval(interval_date, 'month')

        query = Report.query.filter(Report.term_firm_id == firm.id)
        query = query.filter(Report.status == Report.STATUS_COMPLETE)
        query = query.filter(Report.term_id.in_(comission_terms))
        query = query.filter(
            Report.creation_date.between(interval[0], interval[1]))
        reports = query.all()

        if not len(reports):
            log.debug('Empty report for firm id %s, date %s' %
                      (firm_id, search_date))
            return False

        query = PaymentAccount.query.filter(PaymentAccount.firm_id == firm.id)
        query = query.filter(
            PaymentAccount.status == PaymentAccount.STATUS_GENERATED)
        query = query.filter(
            func.DATE(PaymentAccount.generated_date) == func.DATE(search_date))

        account = query.first()
        if not account:
            account = PaymentAccount()
            account.firm_id = firm.id
            account.generated_date = search_date

        account.items_count = len(reports)
        account.summ = 0

        for report in reports:
            if firm.transaction_percent > 0:
                comission = float(report.amount) * \
                    (float(firm.transaction_percent) / 100 / 100)
                if firm.transaction_comission > 0 and comission < firm.transaction_comission:
                    comission = firm.transaction_comission

                account.summ = account.summ + comission
            elif firm.transaction_comission > 0:
                account.summ = account.summ + firm.transaction_comission

        account.items_count = len(reports)
        account.item_price = int(
            round(float(account.summ) / account.items_count))

        account.gprs_terms_count = 0

        if firm.gprs_rate:
            terms_used = 0
            gprs_summ = 0

            for term_id in firm_term:
                term = Term.query.get(term_id)
                delta = account.generated_date - term.config_date

                if not term.has_gprs:
                    continue

                if delta.total_seconds() > Term.USED_LAST_MONTH:
                    continue

                terms_used += 1
                gprs_summ += firm.gprs_rate

            if terms_used:
                account.gprs_terms_count = terms_used
                account.summ += gprs_summ

        account.filename = PaymentAccount.get_filename(firm_id, search_date)
        account.save()

        if not account.generate_pdf():
            log.error('Not generate account for firm id %s, date %s' %
                      (firm_id, search_date))
            account.delete()
            return False

        account.save()

        if not send:
            return True

        emails = firm.decode_field(firm.account_email)
        for email in emails:
            mail.send.delay(AccountMessage,
                            to=email,
                            attach='%s/%s' %
                            (app.config['PDF_FOLDER'], account.filename),
                            date_text=account.get_month_year())

        return True
Ejemplo n.º 21
0
    def account_generate(firm_id, search_date, send=True):
        log = logging.getLogger('task')

        firm = Firm.query.get(firm_id)
        if not firm:
            log.error('Not found firm with id %s' % firm_id)
            return False

        firm_term = FirmTerm.get_list_by_firm_id(firm.id, False)
        leased_term = FirmTerm.get_list_by_firm_id(firm.id, True)
        comission_terms = []

        for term_id in (firm_term | leased_term):
            term = Term.query.get(term_id)
            if not term.has_comission:
                continue
            comission_terms.append(term.id)

        interval_date = search_date - timedelta(days=20)
        interval = date_helper.get_date_interval(interval_date, 'month')

        query = Report.query.filter(Report.term_firm_id == firm.id)
        query = query.filter(Report.status == Report.STATUS_COMPLETE)
        query = query.filter(Report.term_id.in_(comission_terms))
        query = query.filter(
            Report.creation_date.between(interval[0], interval[1]))
        reports = query.all()

        if not len(reports):
            log.debug('Empty report for firm id %s, date %s' %
                      (firm_id, search_date))
            return False

        query = PaymentAccount.query.filter(
            PaymentAccount.firm_id == firm.id)
        query = query.filter(
            PaymentAccount.status == PaymentAccount.STATUS_GENERATED)
        query = query.filter(func.DATE(
            PaymentAccount.generated_date) == func.DATE(search_date))

        account = query.first()
        if not account:
            account = PaymentAccount()
            account.firm_id = firm.id
            account.generated_date = search_date

        account.items_count = len(reports)
        account.summ = 0

        for report in reports:
            if firm.transaction_percent > 0:
                comission = float(report.amount) * \
                    (float(firm.transaction_percent) / 100 / 100)
                if firm.transaction_comission > 0 and comission < firm.transaction_comission:
                    comission = firm.transaction_comission

                account.summ = account.summ + comission
            elif firm.transaction_comission > 0:
                account.summ = account.summ + firm.transaction_comission

        account.items_count = len(reports)
        account.item_price = int(
            round(float(account.summ) / account.items_count))

        account.gprs_terms_count = 0

        if firm.gprs_rate:
            terms_used = 0
            gprs_summ = 0

            for term_id in firm_term:
                term = Term.query.get(term_id)
                delta = account.generated_date - term.config_date

                if not term.has_gprs:
                    continue

                if delta.total_seconds() > Term.USED_LAST_MONTH:
                    continue

                terms_used += 1
                gprs_summ += firm.gprs_rate

            if terms_used:
                account.gprs_terms_count = terms_used
                account.summ += gprs_summ

        account.filename = PaymentAccount.get_filename(firm_id, search_date)
        account.save()

        if not account.generate_pdf():
            log.error('Not generate account for firm id %s, date %s' %
                      (firm_id, search_date))
            account.delete()
            return False

        account.save()

        if not send:
            return True

        emails = firm.decode_field(firm.account_email)
        for email in emails:
            mail.send.delay(
                AccountMessage,
                to=email,
                attach='%s/%s' % (app.config['PDF_FOLDER'], account.filename),
                date_text=account.get_month_year())

        return True