def run(self):
     self.logger.info(u"Добавление нового пользователя:")
     self.logger.info(u'=' * 50)
     username = get_single(u'username: '******'password: '******'не удалось создать пользователя')
         exit(-1)
 def run(self):
     self.logger.info(u"Добавление нового пользователя:")
     self.logger.info(u'=' * 50)
     username = get_single(u'username: '******'password: '******'не удалось создать пользователя')
         exit(-1)
Exemple #3
0
def login(email=None, password=None):
    user = UserManager.login_user(email, password)
    if not user:
        raise errors.InvalidLoginOrPassword()

    google_client_id = request.cookies.get('_ga_cid')
    old_user_id = None
    if current_user and not current_user.is_anonymous:
        if not current_user.temporal:
            my_resp = MyResp()
            current_app.session_interface.save_session(current_app, flask.session, my_resp)
            if google_client_id:
                metrics.update_user_info(current_user, google_client_id=google_client_id)
            # noinspection PyUnresolvedReferences
            my_resp = MyResp(json.dumps({"result": my_resp._MyResp__val}), status=200, content_type="application/json")
            return my_resp

        old_user_id = current_user.id

    login_user(user)
    if google_client_id:
        metrics.update_user_info(user, google_client_id=google_client_id)

    if old_user_id:
        new_user_id = user.id
        change_account_data_owner(old_user_id, new_user_id)

    my_resp = MyResp()
    current_app.session_interface.save_session(current_app, flask.session, my_resp)
    # noinspection PyUnresolvedReferences
    my_resp = MyResp(json.dumps({"result": my_resp._MyResp__val}), status=200, content_type="application/json")
    user.last_login_date = datetime.utcnow()
    return my_resp
Exemple #4
0
def login_temporal(guid=None):
    if "X-Forwarded-For" in request.headers and request.headers.getlist("X-Forwarded-For"):
        ip = request.headers.getlist("X-Forwarded-For")[0]
    elif "X-Real-Ip" in request.headers and request.headers.getlist("X-Real-Ip"):
        ip = request.headers.getlist("X-Real-Ip")[0]
    else:
        ip = request.remote_addr

    if ip in current_app.config['OFFICE_IP']:
        test_user = True
    else:
        test_user = False

    user = None
    if current_user and current_user.is_anonymous:
        user = UserManager.create_temp_user()
        if user:
            login_user(user)
            user.last_login_date = datetime.utcnow()
        user.is_tester = test_user

    elif current_user:
        user = current_user

    if not user:
        raise errors.UserNotFound()

    data = get_user_api_structure(user)
    return {"result": data}
Exemple #5
0
    def setUp(self):
        self.app = Flask(__name__)

        self.test_client = self.app.test_client()
        self.init_logging()
        self.init_validator_context()
        self.config = TEST_CONFIG

        self.auth_cookie = None
        load_filters(self.app.jinja_env, self.config)
        self.app_context = self.app.app_context()
        self.app_context.__enter__()
        set_template_loader(self.app.jinja_env)
        init_configuration(self.app, self.config)
        init_blueprints(self.app)
        init_services(self.app)
        init_login_system(self.app)
        init_db(self.app)
        init_plugins()
        self.mailer = celery.conf['MAILER']
        self.mailer.mails = []
        self.sms_sender = celery.conf['SMS_SENDER']
        self.sms_sender.sms = []
        self.user = None
        self.user_profile = None
        UserManager.init(self.config, self.app.logger)
        sql_db.init_app(self.app)
        sql_db.create_all()
        for table in reversed(sql_db.metadata.sorted_tables):
            sql_db.engine.execute(table.delete())

        @self.app.errorhandler(413)
        def catcher(error):
            data_json = json.dumps({
                "error": {
                    "code": errors.FileToLarge.ERROR_CODE,
                    "message": errors.FileToLarge.ERROR_MESSAGE
                }
            })
            result = Response(data_json,
                              mimetype='application/json',
                              status=400)
            result.headers.add('Access-Control-Allow-Credentials', "true")
            result.headers.add('Access-Control-Allow-Origin',
                               "http://%s" % self.config['site_domain'])
            return result
Exemple #6
0
def go_auth_url(go_id):
    if not go_id or not go_id.isalnum():
        abort(404)

    try:
        return redirect(UserManager.authorize_by_url(go_id))
    except Exception:
        pass
    abort(404)
def not_paid_check_and_send(*args, **kwargs):
    config = celery.conf.get('config')

    batch_id = kwargs['batch_id']
    last_change_dt_str = kwargs['last_change_dt_str']

    with celery.conf['flask_app']().app_context():
        logger = current_app.logger
        batch = DocumentBatchDbObject.query.filter_by(id=batch_id).scalar()
        if not batch or not batch.data or batch.status != BatchStatusEnum.BS_FINALISED:
            logger.info("Exit 1")
            return False

        last_change_dt = batch.last_change_dt
        if last_change_dt and isinstance(last_change_dt, datetime):
            if last_change_dt_str != last_change_dt.strftime("%Y-%m-%dT%H:%M:%S"):
                logger.info("Exit 2")
                return True

        if batch.paid:
            return True

        user = batch._owner
        if not user or not user.email:
            logger.info("Exit 3")
            return False

        send_mails = batch.sent_mails or []
        if send_mails and "please_pay_finalised" in send_mails or "please_pay_finalised_double" in send_mails:
            logger.info("Exit 4")
            return False

        mail_type = "please_pay_finalised" if "please_finalise" not in send_mails else "please_pay_finalised_double"

        batch_url = u"%s://%s/ooo/?id=%s" % (config['WEB_SCHEMA'], config['DOMAIN'], batch_id)
        batch_url = utm_args(batch_url, mail_type, user.id)

        tmpl_data = {
            "short_name": batch.data.get('short_name', ""),
            "domain": config['DOMAIN'],
            "schema": config['WEB_SCHEMA'],
            "user_id": str(user.id),
            "batch_url": UserManager.make_auth_url(batch_url, user).get_url(config)
        }

        send_email.send_email(user.email, mail_type, **tmpl_data)

        mails_sent = set(send_mails)
        mails_sent.add(mail_type)
        DocumentBatchDbObject.query.filter_by(id=batch_id).update({
            'sent_mails': list(mails_sent)
        })
        sqldb.session.commit()
        logger.info("Exit 5")
        return True
    def setUp(self):
        self.app = Flask(__name__)

        self.test_client = self.app.test_client()
        self.init_logging()
        self.init_validator_context()
        self.config = TEST_CONFIG

        self.auth_cookie = None
        load_filters(self.app.jinja_env, self.config)
        self.app_context = self.app.app_context()
        self.app_context.__enter__()
        set_template_loader(self.app.jinja_env)
        init_configuration(self.app, self.config)
        init_blueprints(self.app)
        init_services(self.app)
        init_login_system(self.app)
        init_db(self.app)
        init_plugins()
        self.mailer = celery.conf['MAILER']
        self.mailer.mails = []
        self.sms_sender = celery.conf['SMS_SENDER']
        self.sms_sender.sms = []
        self.user = None
        self.user_profile = None
        UserManager.init(self.config, self.app.logger)
        sql_db.init_app(self.app)
        sql_db.create_all()
        for table in reversed(sql_db.metadata.sorted_tables):
            sql_db.engine.execute(table.delete())

        @self.app.errorhandler(413)
        def catcher(error):
            data_json = json.dumps({"error": {"code": errors.FileToLarge.ERROR_CODE, "message": errors.FileToLarge.ERROR_MESSAGE}})
            result = Response(data_json, mimetype='application/json', status=400)
            result.headers.add('Access-Control-Allow-Credentials', "true")
            result.headers.add('Access-Control-Allow-Origin', "http://%s" % self.config['site_domain'])
            return result
Exemple #9
0
def confirm_account(code=None, user_id=None):
    if len(code) != current_app.config['max_activation_link_length'] and \
                    len(code) != current_app.config['digital_activation_link_length']:
        raise errors.InvalidParameterValue('code')

    if len(code) == current_app.config['digital_activation_link_length'] and not user_id:
        raise errors.MissingRequiredParameter('code')

    link_type = ConfirmationLinkTypeEnum.CLT_MOBILE if (
        len(code) == current_app.config['digital_activation_link_length']) else ConfirmationLinkTypeEnum.CLT_EMAIL
    user = UserManager.confirm_email_or_mobile(code, user_id if user_id else None, link_type)
    if not user:
        raise errors.UserNotFound()

    data = get_user_api_structure(user)
    return {"result": data}
Exemple #10
0
def password_change(user_id=None, email=None, code=None, old_password=None, new_password=None):
    email = email.lower() if email else u""

    if not user_id and email:
        # find user based on email
        user = AuthUser.query.filter_by(email=email).first()
        if not user:
            raise errors.UserNotFound()
        user_id = user.uuid
    elif not user_id:
        raise errors.InvalidParameterValue('user_id')

    user = UserManager.change_password(user_id, code, old_password, new_password)
    if user and not current_user.is_authenticated:
        login_user(user)
    return {"result": True}
def not_finalised_check_and_send(batch_id=None, last_change_dt_str=None):
    if not batch_id or not last_change_dt_str:
        return False

    config = celery.conf.get('config')

    with celery.conf['flask_app']().app_context():
        batch = DocumentBatchDbObject.query.filter_by(id=batch_id, deleted=False, finalisation_count=0).scalar()
        if not batch or batch.status not in (BatchStatusEnum.BS_NEW, BatchStatusEnum.BS_EDITED):
            return False

        last_change_dt = batch.last_change_dt
        if last_change_dt and isinstance(last_change_dt, datetime):
            if last_change_dt_str != last_change_dt.strftime("%Y-%m-%dT%H:%M:%S"):
                return True

        mail_type = 'please_finalise'
        if mail_type in (batch.sent_mails or []):
            return False
        mails_sent = set(batch.sent_mails or [])

        user = batch._owner
        if not user or not user.email:
            return False
        batch_data = batch.data

        batch_url = u"%s://%s/ooo/?id=%s" % (config['WEB_SCHEMA'], config['DOMAIN'], batch_id)

        tmpl_data = {
            "short_name": batch_data.get('short_name', ""),
            "domain": config['DOMAIN'],
            "schema": config['WEB_SCHEMA'],
            "user_id": str(user.id),
            "batch_url": UserManager.make_auth_url(batch_url, user).get_url(config)
        }

        send_email.send_email(user.email, mail_type, **tmpl_data)

        mails_sent.add(mail_type)
        DocumentBatchDbObject.query.filter_by(id=batch_id).update({
            'sent_mails': list(mails_sent)
        })
        sqldb.session.commit()
        return True
    def run(self):
        self.logger.info(u"Отправка письма о регистрации компании")
        self.logger.info(u'=' * 50)

        batch_id = get_single(u'Batch id: ')

        batch = DocumentBatchDbObject.query.filter_by(id=batch_id, batch_type=DocumentBatchTypeEnum.DBT_NEW_LLC).first()
        if not batch:
            self.logger.info(u'Batch not found')
            return

        if not batch.result_fields or 'ifns_reg_info' not in batch.result_fields:
            self.logger.info(u'Company not registered')
            return

        reg_info = batch.result_fields['ifns_reg_info']
        if 'status' not in reg_info or reg_info['status'] != 'registered' or not reg_info['reg_date'] or not reg_info['ogrn']:
            self.logger.info(u'Company not registered')
            return

        ogrn = reg_info['ogrn']
        reg_date = reg_info['reg_date'].strptime("%d.%m.%Y")

        recipient = batch._owner.email
        if not recipient:
            self.logger.info(u'Company owner has no email')
            return

        short_name = batch.data.get('short_name', u"")
        doc_rec_type = batch.data.get('obtain_way', None)

        ifns_book_doc_receive_url = "%s://%s/ip/?id=%s" % (self.config['WEB_SCHEMA'], self.config['DOMAIN'], batch_id)
        ifns_book_doc_receive_url = utm_args(ifns_book_doc_receive_url, 'ifns_ip_reg_success', batch._owner_id) + u"#page=obtaining"
        ifns_book_doc_receive_url = UserManager.make_auth_url(ifns_book_doc_receive_url, batch._owner).get_url(self.config)

        docs_recipient_fio = u""
        if doc_rec_type == DocumentDeliveryTypeStrEnum.DDT_ISSUE_TO_THE_APPLICANT:
            doc = BatchDocumentDbObject.query.filter_by(batch=batch,
                                                        document_type=DocumentTypeEnum.DT_P11001).first()
            if doc:
                founders = doc.data['founders']
                for founder in founders:
                    if founder.get('documents_recipient_type', '') != '':
                        person = founder.get('person', None)
                        if person and '_id' in person:
                            person_obj = PrivatePersonDbObject.query.filter_by(
                                id=person['_id']).scalar()
                            if person_obj:
                                pp = PrivatePerson.db_obj_to_field(person_obj)
                                if pp:
                                    docs_recipient_fio = pp.full_name
                        else:
                            company = founder.get('company', None)
                            if company:
                                company_db_object = CompanyDbObject.query.filter_by(
                                    id=company['_id']).scalar()
                                if company_db_object:
                                    cc = CompanyObject.db_obj_to_field(company_db_object)
                                    if cc and cc.general_manager and cc.general_manager.initialized:
                                        docs_recipient_fio = cc.general_manager.full_name
        elif doc_rec_type == DocumentDeliveryTypeStrEnum.DDT_ISSUE_TO_THE_APPLICANT_OR_AGENT:
            doc = BatchDocumentDbObject.query.filter_by(batch=batch,
                                                        document_type=DocumentTypeEnum.DT_DOVERENNOST_OBTAIN).first()

            if doc:
                doc_obtain_person = doc.data.get('doc_obtain_person', None)
                if doc_obtain_person and '_id' in doc_obtain_person:
                    person_obj = PrivatePersonDbObject.query.filter_by(
                        id=doc_obtain_person['_id']).scalar()
                    if person_obj:
                        pp = PrivatePerson.db_obj_to_field(person_obj)
                        if pp:
                            docs_recipient_fio = pp.full_name

        send_email.send_email(recipient,
            'ifns_llc_reg_success',
            short_name=short_name,
            doc_rec_by_email=(doc_rec_type == DocumentDeliveryTypeStrEnum.DDT_SEND_BY_MAIL),
            doc_rec_by_responsible=(
                doc_rec_type == DocumentDeliveryTypeStrEnum.DDT_ISSUE_TO_THE_APPLICANT_OR_AGENT),
            ifns_book_doc_receive_url=ifns_book_doc_receive_url,
            schema=self.config['WEB_SCHEMA'],
            domain=self.config['DOMAIN'],
            ogrn=ogrn,
            docs_ready_date=u"%d %s %s года" % (
                reg_date.day, get_russian_month_skl(reg_date.month), reg_date.year),
            docs_recipient_fio=docs_recipient_fio,
            obtain_person_fio=u"",
            service_startup=datetime.utcnow() < datetime(2015, 6, 1),
            user_id=str(batch._owner_id))
        self.logger.info(u'Sent %s to %s' % ('ifns_llc_reg_success', recipient))
Exemple #13
0

load_filters(app.jinja_env, app.config)
set_template_loader(app.jinja_env)

init_blueprints(app)
init_services(app)
init_sql_db(app)
init_plugins()
init_flask_signals()

#noinspection PyUnresolvedReferences
init_login_system(app, app.config)
app.secret_key = app.config['secret_key']
from fw.auth.user_manager import UserManager
UserManager.init(app.config, app.logger)


@app.errorhandler(413)
def catcher(error):
    data_json = json.dumps({
        "error": {
            "code": errors.FileToLarge.ERROR_CODE,
            "message": errors.FileToLarge.ERROR_MESSAGE
        }
    })
    result = Response(data_json, mimetype='application/json', status=400)
    result.headers.add('Access-Control-Allow-Credentials', "true")
    result.headers.add('Access-Control-Allow-Origin',
                       "http://%s" % app.config['site_domain'])
    return result
    def run(self):
        #        self.logger.info(u"Проверка статуса регистрации компаний")
        #        self.logger.info(u'=' * 50)

        is_production = not self.config['STAGING'] and not self.config['DEBUG']
        days_30 = timedelta(days=30)
        # get list of testers
        from services.ifns.data_model.models import IfnsBookingObject

        # and exclude their batches
        query = DocumentBatchDbObject.query.filter(
            DocumentBatchDbObject.status == BatchStatusEnum.BS_FINALISED,
            DocumentBatchDbObject.paid == True,
            DocumentBatchDbObject.finalisation_date >=
            datetime.now() - days_30)
        if is_production:
            query = query.join(AuthUser).filter(AuthUser.is_tester == False)

        skip_statuses = (IfnsRegStatusEnum.IRS_REGISTERED,
                         IfnsRegStatusEnum.IRS_REGISTRATION_DECLINED)
        for batch in query:
            status = (batch.result_fields
                      or {}).get('ifns_reg_info', {}).get('status', 'unknown')
            if status in skip_statuses:
                continue

            batch_id = batch.id
            # self.logger.info(u"%s" % unicode(batch_id))

            ifns = (batch.result_fields or {}).get('ifns', None)

            #self.logger.info(u"ifns: %s" % ifns)
            ifns_data = ifns_manager.get_ifns_data(ifns)
            if ifns_data and ifns_data.rou and 'code' in ifns_data.rou:
                ifns = ifns_data.rou['code']

            full_name = ""
            short_name = ""
            if batch.batch_type == DocumentBatchTypeEnum.DBT_NEW_LLC:
                full_name = batch.data.get('full_name', None)
                short_name = batch.data.get('short_name', None)
            elif batch.batch_type == DocumentBatchTypeEnum.DBT_NEW_IP:
                try:
                    reg_responsible_person = batch.data.get('person', None)
                    person_field = ObjectRefField()
                    person_field.parse_raw_value(reg_responsible_person, {},
                                                 api_data=False,
                                                 update=False)
                    full_name = person_field.full_name
                    short_name = person_field.short_name
                except Exception:
                    self.logger.exception(u"Failed to parse IP person")
            else:
                self.logger.exception(u"Unknown batch type for batch %s" %
                                      str(batch['_id']))

            doc_rec_type = batch.data.get('obtain_way', None)
            application_form = batch.data.get('registration_way', None)
            if batch.batch_type == DocumentBatchTypeEnum.DBT_NEW_LLC:
                applicant_fio = u""
            elif batch.batch_type == DocumentBatchTypeEnum.DBT_NEW_IP:
                applicant_fio = full_name
            for doc in batch._documents:
                if doc.document_type == DocumentTypeEnum.DT_REGISTRATION_FEE_INVOICE:
                    founder_applicant = doc.data.get('founder_applicant', None)
                    if founder_applicant:
                        try:
                            founder_app_field = FounderObject()
                            founder_app_field.parse_raw_value(
                                founder_applicant, {},
                                api_data=False,
                                update=False)
                            applicant_fio = founder_app_field.full_name
                        except Exception:
                            self.logger.exception(
                                u"Failed to parse founder object")
                    break

            if application_form == RegistrationWay.RW_RESPONSIBLE_PERSON:
                reg_responsible_person = batch.data.get(
                    'reg_responsible_person', None)
                if reg_responsible_person:
                    try:
                        reg_responsible_person_field = ObjectRefField()
                        reg_responsible_person_field.parse_raw_value(
                            reg_responsible_person, {},
                            api_data=False,
                            update=False)
                        applicant_fio = reg_responsible_person_field.full_name
                    except Exception:
                        self.logger.exception(u"Failed to parse person")

            ifns_booking = IfnsBookingObject.query.filter_by(
                batch_id=batch_id,
                service_id=IfnsServiceEnum.IS_REG_COMPANY,
                _discarded=False).first()
            if ifns_booking:
                dt = ifns_booking.date
                if dt and is_production and datetime.now() < dt:
                    self.logger.info(u"Too early - skip")
                    continue

            # self.logger.info(u"Checking batch %s" % unicode(batch_id))
            date_from = batch.finalisation_date - timedelta(days=5)
            date_to = date_from + timedelta(days=30)
            result = current_app.external_tools.get_ifns_registrations(
                full_name,
                date_from=date_from,
                date_to=date_to,
                ifns=ifns,
                service_nalog_ru_url=self.config['SERVICE_NALOG_RU_URL'],
                logger=self.logger) or []

            if not result:
                # self.logger.info(u"No reservations for batch %s" % unicode(batch_id))
                continue
            else:
                for item in result:
                    try:
                        self.logger.info(
                            u"Found reservation info for batch %s (%s)" %
                            (batch_id,
                             json.dumps(item, default=lambda x: unicode(x))))
                        if 'status' not in item:
                            continue
                        status = item['status']
                        batch_result_fields = batch.result_fields or {}

                        if status == 'registered' and ('ogrn' in item
                                                       or 'ogrnip' in item):
                            ogrn = item.get('ogrn')
                            ogrnip = item.get('ogrnip')
                            reg_date = None
                            try:
                                reg_date = item.get('reg_date', None)
                                if reg_date:
                                    reg_date = datetime.strptime(
                                        reg_date, "%d.%m.%Y")
                            except Exception:
                                self.logger.exception(
                                    u"Failed to convert reg_date")
                            reg_info = {
                                'status': 'registered',
                                'reg_date': reg_date,
                            }
                            if ogrn:
                                reg_info['ogrn'] = ogrn
                            elif ogrnip:
                                reg_info['ogrnip'] = ogrnip

                            booking = IfnsBookingObject.query.filter_by(
                                batch_id=batch_id,
                                service_id=IfnsServiceEnum.IS_REG_COMPANY,
                                _discarded=False).first()
                            if booking:
                                booking.reg_info = reg_info
                                sqldb.session.commit()

                            batch_result_fields['ifns_reg_info'] = {
                                'status': 'registered',
                                'reg_date': reg_date,
                                'full_name': full_name
                            }
                            if ogrn:
                                batch_result_fields['ifns_reg_info'][
                                    'ogrn'] = ogrn
                            elif ogrnip:
                                batch_result_fields['ifns_reg_info'][
                                    'ogrnip'] = ogrnip

                            DocumentBatchDbObject.query.filter_by(
                                id=batch.id).update(
                                    {'result_fields': batch_result_fields})
                            sqldb.session.commit()
                            recipient = batch._owner.email or u""
                            obtain_person_fio = u""
                            if not recipient:
                                self.logger.warn(
                                    u"Failed to send ifns reg notify to user %s - no email address"
                                    % batch._owner_id)
                            else:
                                docs_recipient_fio = ""
                                # Batch Type specific logic
                                if batch.batch_type == DocumentBatchTypeEnum.DBT_NEW_LLC:
                                    # TODO: This should be incapsulated
                                    if doc_rec_type == DocumentDeliveryTypeStrEnum.DDT_ISSUE_TO_THE_APPLICANT:
                                        doc = BatchDocumentDbObject.query.filter_by(
                                            batch=batch,
                                            document_type=DocumentTypeEnum.
                                            DT_P11001).first()
                                        if doc:
                                            founders = doc.data['founders']
                                            for founder in founders:
                                                if founder.get(
                                                        'documents_recipient_type',
                                                        '') != '':
                                                    person = founder.get(
                                                        'person', None)
                                                    if person and '_id' in person:
                                                        person_obj = PrivatePersonDbObject.query.filter_by(
                                                            id=person['_id']
                                                        ).scalar()
                                                        if person_obj:
                                                            pp = PrivatePerson.db_obj_to_field(
                                                                person_obj)
                                                            if pp:
                                                                docs_recipient_fio = pp.full_name
                                                    else:
                                                        company = founder.get(
                                                            'company', None)
                                                        if company:
                                                            company_db_object = CompanyDbObject.query.filter_by(
                                                                id=company[
                                                                    '_id']
                                                            ).scalar()
                                                            if company_db_object:
                                                                cc = CompanyObject.db_obj_to_field(
                                                                    company_db_object
                                                                )
                                                                if cc and cc.general_manager and cc.general_manager.initialized:
                                                                    docs_recipient_fio = cc.general_manager.full_name
                                    elif doc_rec_type == DocumentDeliveryTypeStrEnum.DDT_ISSUE_TO_THE_APPLICANT_OR_AGENT:
                                        doc = BatchDocumentDbObject.query.filter_by(
                                            batch=batch,
                                            document_type=DocumentTypeEnum.
                                            DT_DOVERENNOST_OBTAIN).first()

                                        if doc:
                                            doc_obtain_person = doc.data.get(
                                                'doc_obtain_person', None)
                                            if doc_obtain_person and '_id' in doc_obtain_person:
                                                person_obj = PrivatePersonDbObject.query.filter_by(
                                                    id=doc_obtain_person['_id']
                                                ).scalar()
                                                if person_obj:
                                                    pp = PrivatePerson.db_obj_to_field(
                                                        person_obj)
                                                    if pp:
                                                        docs_recipient_fio = pp.full_name

                                        doc = BatchDocumentDbObject.query.filter_by(
                                            batch=batch,
                                            document_type=DocumentTypeEnum.
                                            DT_P11001).first()
                                        if doc:
                                            founders = doc.data['founders']
                                            for founder in founders:
                                                if founder.get(
                                                        'documents_recipient_type',
                                                        '') != '':
                                                    person = founder.get(
                                                        'person', None)
                                                    if person and '_id' in person:
                                                        person_obj = PrivatePersonDbObject.query.filter_by(
                                                            id=person['_id']
                                                        ).scalar()
                                                        if person_obj:
                                                            pp = PrivatePerson.db_obj_to_field(
                                                                person_obj)
                                                            if pp:
                                                                obtain_person_fio = pp.full_name
                                                    else:
                                                        company = founder.get(
                                                            'company', None)
                                                        if company:
                                                            company_db_object = CompanyDbObject.query.filter_by(
                                                                id=company[
                                                                    '_id']
                                                            ).scalar()
                                                            if company_db_object:
                                                                cc = CompanyObject.db_obj_to_field(
                                                                    company_db_object
                                                                )
                                                                if cc and cc.general_manager and cc.general_manager.initialized:
                                                                    obtain_person_fio = cc.general_manager.full_name
                                    ifns_book_doc_receive_url = "%s://%s/ooo/?id=%s" % (
                                        self.config['WEB_SCHEMA'],
                                        self.config['DOMAIN'],
                                        unicode(batch_id))
                                    ifns_book_doc_receive_url = utm_args(
                                        ifns_book_doc_receive_url,
                                        "ifns_llc_reg_success",
                                        batch._owner_id) + u"#page=obtaining"
                                    ifns_book_doc_receive_url = UserManager.make_auth_url(
                                        ifns_book_doc_receive_url,
                                        batch._owner).get_url(self.config)

                                    send_email.send_email.delay(
                                        recipient,
                                        'ifns_llc_reg_success',
                                        short_name=short_name,
                                        doc_rec_by_email=(
                                            doc_rec_type ==
                                            DocumentDeliveryTypeStrEnum.
                                            DDT_SEND_BY_MAIL),
                                        doc_rec_by_responsible=(
                                            doc_rec_type ==
                                            DocumentDeliveryTypeStrEnum.
                                            DDT_ISSUE_TO_THE_APPLICANT_OR_AGENT
                                        ),
                                        ifns_book_doc_receive_url=
                                        ifns_book_doc_receive_url,
                                        schema=self.config['WEB_SCHEMA'],
                                        domain=self.config['DOMAIN'],
                                        ogrn=ogrn,
                                        docs_ready_date=u"%d %s %s года" %
                                        (reg_date.day,
                                         get_russian_month_skl(
                                             reg_date.month), reg_date.year),
                                        docs_recipient_fio=docs_recipient_fio,
                                        obtain_person_fio=obtain_person_fio,
                                        service_startup=datetime.now() <
                                        datetime(2015, 6, 1),
                                        user_id=str(batch._owner_id))
                                elif batch.batch_type == DocumentBatchTypeEnum.DBT_NEW_IP:

                                    if doc_rec_type == IPDocumentDeliveryTypeStrEnum.IP_DDT_RESPONSIBLE_PERSON:
                                        for doc in BatchDocumentDbObject.query.filter(
                                                BatchDocumentDbObject.batch ==
                                                batch,
                                                BatchDocumentDbObject.
                                                document_type.in_((
                                                    DocumentTypeEnum.
                                                    DT_IP_DOV_FILING_RECEIVING_DOCS,
                                                    DocumentTypeEnum.
                                                    DT_IP_DOV_RECEIVING_DOCS
                                                ))):
                                            person = doc.data.get(
                                                'ip_responsible_person', None)
                                            if person and '_id' in person:
                                                person_obj = PrivatePersonDbObject.query.filter_by(
                                                    id=person['_id']).scalar()
                                                if person_obj:
                                                    pp = PrivatePerson.db_obj_to_field(
                                                        person_obj)
                                                    if pp:
                                                        docs_recipient_fio = pp.full_name
                                                        break

                                    ifns_book_doc_receive_url = "%s://%s/ip/?id=%s" % (
                                        self.config['WEB_SCHEMA'],
                                        self.config['DOMAIN'], batch_id)
                                    ifns_book_doc_receive_url = utm_args(
                                        ifns_book_doc_receive_url,
                                        'ifns_ip_reg_success',
                                        batch._owner_id) + u"#page=obtaining"
                                    ifns_book_doc_receive_url = UserManager.make_auth_url(
                                        ifns_book_doc_receive_url,
                                        batch._owner).get_url(self.config)

                                    send_email.send_email.delay(
                                        recipient,
                                        'ifns_ip_reg_success',
                                        short_name=short_name,
                                        doc_rec_by_email=(
                                            doc_rec_type ==
                                            IPDocumentDeliveryTypeStrEnum.
                                            IP_DDT_MAIL),
                                        doc_rec_by_responsible=(
                                            doc_rec_type ==
                                            IPDocumentDeliveryTypeStrEnum.
                                            IP_DDT_RESPONSIBLE_PERSON),
                                        ifns_book_doc_receive_url=
                                        ifns_book_doc_receive_url,
                                        schema=self.config['WEB_SCHEMA'],
                                        domain=self.config['DOMAIN'],
                                        ogrnip=ogrnip,
                                        docs_ready_date=u"%d %s %s года" %
                                        (reg_date.day,
                                         get_russian_month_skl(
                                             reg_date.month), reg_date.year),
                                        docs_recipient_fio=docs_recipient_fio,
                                        obtain_person_fio=obtain_person_fio,
                                        service_startup=datetime.now() <
                                        datetime(2015, 6, 1),
                                        user_id=str(batch._owner_id))
                            self.notify_admin(True,
                                              short_name,
                                              batch_id,
                                              application_form,
                                              doc_rec_type,
                                              applicant_fio,
                                              recipient,
                                              ogrn=ogrn,
                                              ogrnip=ogrnip,
                                              batch_type=batch.batch_type)
                        elif status == 'registration_declined':
                            reg_date = None
                            try:
                                reg_date = item.get('reg_date', None)
                                if reg_date:
                                    reg_date = datetime.strptime(
                                        reg_date, "%d.%m.%Y")
                            except Exception:
                                self.logger.exception(
                                    u"Failed to convert reg_date")

                            IfnsBookingObject.query.filter_by(
                                batch_id=batch_id,
                                service_id=IfnsServiceEnum.IS_REG_COMPANY,
                                _discarded=False).update({
                                    'reg_info': {
                                        'status': 'registration_declined',
                                        'reg_date': reg_date
                                    }
                                })
                            sqldb.session.commit()
                            batch_result_fields['ifns_reg_info'] = {
                                'status': 'registration_declined',
                                'reg_date': reg_date,
                                'full_name': full_name
                            }
                            recipient = batch._owner.email or u""
                            if not recipient:
                                self.logger.warn(
                                    u"Failed to send ifns reg notify to user %s - no email address"
                                    % batch._owner_id)
                            else:
                                if batch.batch_type == DocumentBatchTypeEnum.DBT_NEW_LLC:
                                    ifns_book_doc_receive_url = "%s://%s/ooo/?id=%s" % (
                                        self.config['WEB_SCHEMA'],
                                        self.config['DOMAIN'], batch_id)
                                    ifns_book_doc_receive_url = utm_args(
                                        ifns_book_doc_receive_url,
                                        'ifns_llc_reg_fail',
                                        batch._owner_id) + u"#page=refusing"
                                    ifns_book_doc_receive_url = UserManager.make_auth_url(
                                        ifns_book_doc_receive_url,
                                        batch._owner).get_url(self.config)

                                    send_email.send_email.delay(
                                        recipient,
                                        'ifns_llc_reg_fail',
                                        short_name=short_name,
                                        doc_rec_by_email=(
                                            doc_rec_type ==
                                            DocumentDeliveryTypeStrEnum.
                                            DDT_SEND_BY_MAIL),
                                        ifns_book_doc_receive_url=
                                        ifns_book_doc_receive_url,
                                        schema=self.config['WEB_SCHEMA'],
                                        domain=self.config['DOMAIN'],
                                        user_id=batch._owner_id)
                                elif batch.batch_type == DocumentBatchTypeEnum.DBT_NEW_IP:
                                    ifns_book_doc_receive_url = "%s://%s/ip/?id=%s" % (
                                        self.config['WEB_SCHEMA'],
                                        self.config['DOMAIN'], batch_id)
                                    ifns_book_doc_receive_url = utm_args(
                                        ifns_book_doc_receive_url,
                                        'ifns_ip_reg_fail',
                                        batch._owner_id) + u"#page=refusing"
                                    ifns_book_doc_receive_url = UserManager.make_auth_url(
                                        ifns_book_doc_receive_url,
                                        batch._owner).get_url(self.config)
                                    send_email.send_email.delay(
                                        recipient,
                                        'ifns_ip_reg_fail',
                                        short_name=short_name,
                                        doc_rec_by_email=(
                                            doc_rec_type ==
                                            IPDocumentDeliveryTypeStrEnum.
                                            IP_DDT_MAIL),
                                        ifns_book_doc_receive_url=
                                        ifns_book_doc_receive_url,
                                        schema=self.config['WEB_SCHEMA'],
                                        domain=self.config['DOMAIN'],
                                        user_id=batch._owner_id)
                            DocumentBatchDbObject.query.filter_by(
                                id=batch.id).update(
                                    {'result_fields': batch_result_fields})
                            sqldb.session.commit()
                            self.notify_admin(False,
                                              short_name,
                                              batch_id,
                                              application_form,
                                              doc_rec_type,
                                              applicant_fio,
                                              recipient,
                                              batch_type=batch.batch_type)
                        elif status == 'progress':
                            IfnsBookingObject.query.filter_by(
                                batch_id=batch_id,
                                service_id=IfnsServiceEnum.IS_REG_COMPANY,
                                _discarded=False).update({
                                    'reg_info': {
                                        'status': 'progress',
                                        'reg_date': item.get('reg_date', None)
                                    }
                                })
                            batch_result_fields['ifns_reg_info'] = {
                                'status': 'progress',
                                'reg_date': item.get('reg_date', None),
                                'full_name': full_name
                            }
                            DocumentBatchDbObject.query.filter_by(
                                id=batch.id).update(
                                    {'result_fields': batch_result_fields})
                            sqldb.session.commit()
                        else:
                            raise Exception()

                        break
                    except Exception:
                        self.logger.exception(u"Failed to handle result")
    def run(self):
        self.logger.info(u"Отправка письма о регистрации компании")
        self.logger.info(u'=' * 50)

        batch_id = get_single(u'Batch id: ')

        batch = DocumentBatchDbObject.query.filter_by(
            id=batch_id, batch_type=DocumentBatchTypeEnum.DBT_NEW_LLC).first()
        if not batch:
            self.logger.info(u'Batch not found')
            return

        if not batch.result_fields or 'ifns_reg_info' not in batch.result_fields:
            self.logger.info(u'Company not registered')
            return

        reg_info = batch.result_fields['ifns_reg_info']
        if 'status' not in reg_info or reg_info[
                'status'] != 'registered' or not reg_info[
                    'reg_date'] or not reg_info['ogrn']:
            self.logger.info(u'Company not registered')
            return

        ogrn = reg_info['ogrn']
        reg_date = reg_info['reg_date'].strptime("%d.%m.%Y")

        recipient = batch._owner.email
        if not recipient:
            self.logger.info(u'Company owner has no email')
            return

        short_name = batch.data.get('short_name', u"")
        doc_rec_type = batch.data.get('obtain_way', None)

        ifns_book_doc_receive_url = "%s://%s/ip/?id=%s" % (
            self.config['WEB_SCHEMA'], self.config['DOMAIN'], batch_id)
        ifns_book_doc_receive_url = utm_args(
            ifns_book_doc_receive_url, 'ifns_ip_reg_success',
            batch._owner_id) + u"#page=obtaining"
        ifns_book_doc_receive_url = UserManager.make_auth_url(
            ifns_book_doc_receive_url, batch._owner).get_url(self.config)

        docs_recipient_fio = u""
        if doc_rec_type == DocumentDeliveryTypeStrEnum.DDT_ISSUE_TO_THE_APPLICANT:
            doc = BatchDocumentDbObject.query.filter_by(
                batch=batch, document_type=DocumentTypeEnum.DT_P11001).first()
            if doc:
                founders = doc.data['founders']
                for founder in founders:
                    if founder.get('documents_recipient_type', '') != '':
                        person = founder.get('person', None)
                        if person and '_id' in person:
                            person_obj = PrivatePersonDbObject.query.filter_by(
                                id=person['_id']).scalar()
                            if person_obj:
                                pp = PrivatePerson.db_obj_to_field(person_obj)
                                if pp:
                                    docs_recipient_fio = pp.full_name
                        else:
                            company = founder.get('company', None)
                            if company:
                                company_db_object = CompanyDbObject.query.filter_by(
                                    id=company['_id']).scalar()
                                if company_db_object:
                                    cc = CompanyObject.db_obj_to_field(
                                        company_db_object)
                                    if cc and cc.general_manager and cc.general_manager.initialized:
                                        docs_recipient_fio = cc.general_manager.full_name
        elif doc_rec_type == DocumentDeliveryTypeStrEnum.DDT_ISSUE_TO_THE_APPLICANT_OR_AGENT:
            doc = BatchDocumentDbObject.query.filter_by(
                batch=batch,
                document_type=DocumentTypeEnum.DT_DOVERENNOST_OBTAIN).first()

            if doc:
                doc_obtain_person = doc.data.get('doc_obtain_person', None)
                if doc_obtain_person and '_id' in doc_obtain_person:
                    person_obj = PrivatePersonDbObject.query.filter_by(
                        id=doc_obtain_person['_id']).scalar()
                    if person_obj:
                        pp = PrivatePerson.db_obj_to_field(person_obj)
                        if pp:
                            docs_recipient_fio = pp.full_name

        send_email.send_email(
            recipient,
            'ifns_llc_reg_success',
            short_name=short_name,
            doc_rec_by_email=(
                doc_rec_type == DocumentDeliveryTypeStrEnum.DDT_SEND_BY_MAIL),
            doc_rec_by_responsible=(doc_rec_type == DocumentDeliveryTypeStrEnum
                                    .DDT_ISSUE_TO_THE_APPLICANT_OR_AGENT),
            ifns_book_doc_receive_url=ifns_book_doc_receive_url,
            schema=self.config['WEB_SCHEMA'],
            domain=self.config['DOMAIN'],
            ogrn=ogrn,
            docs_ready_date=u"%d %s %s года" %
            (reg_date.day, get_russian_month_skl(
                reg_date.month), reg_date.year),
            docs_recipient_fio=docs_recipient_fio,
            obtain_person_fio=u"",
            service_startup=datetime.utcnow() < datetime(2015, 6, 1),
            user_id=str(batch._owner_id))
        self.logger.info(u'Sent %s to %s' %
                         ('ifns_llc_reg_success', recipient))
Exemple #16
0
def render_batch_raw(batch_db_object_id, render_only_failed_docs=False):
    request = current_task.request
    config = celery.conf.get('config')
    eager = celery.conf['CELERY_ALWAYS_EAGER']
    app = celery.conf['flask_app']()
    logger = app.logger

    from fw.documents.batch_manager import BatchManager
    with app.app_context():
        batch_db_object = DocumentBatchDbObject.query.filter_by(id=batch_db_object_id).first()
        if not batch_db_object:
            logger.error(u"Failed to find batch with id %s in collection %s in db %s" % (
                batch_db_object_id, DocumentBatchDbObject.COLLECTION_NAME, config['db_name']))
            return False

        batch_db_object.current_task_id = request.id
        batch_db_object.batch_rendering_start = datetime.utcnow()
        sqldb.session.commit()

        task_holder = BatchTaskFileIdHolder(request.id, config, batch_db_object) if not eager else FakeTaskHolder()
        with task_holder as task_file:
            logger.info(u"Generating documents for batch %s" % batch_db_object_id)

            try:
                batch_type = batch_db_object.batch_type

                batch_manager = BatchManager.init(batch_db_object)
                batch_descriptor = DocRequisitiesStorage.get_batch_descriptor(batch_type)
                doc_types_allowed_to_deferred_rendering = batch_descriptor.get('deferred_render_docs', [])

                watermark = None if batch_db_object.paid else "notpaid_watermark.png"

                has_errors = False
                failed_doc_types = set()
                for doc in batch_db_object._documents:
                    # if not task_file.exists():
                    #     logger.warning(u"Task with id %s has been revoked" % request.id)
                    #     batch_db_object.status = BatchStatusEnum.BS_EDITED
                    #     sqldb.session.commit()
                    #     return True

                    doc_type = doc.document_type
                    if render_only_failed_docs and doc.status != UserDocumentStatus.DS_RENDERING_FAILED:
                        continue

                    render_doc_file = batch_type == DocumentBatchTypeEnum.DBT_NEW_LLC and batch_db_object.paid
                    if not render_single_document(doc, batch_manager.get_title(doc_type), watermark,
                                                  config, logger, request.id, render_doc_file):
                        has_errors = True
                        if doc_type not in doc_types_allowed_to_deferred_rendering:
                            if not render_only_failed_docs:
                                batch_db_object.status = BatchStatusEnum.BS_EDITED
                                batch_db_object.error_info = {
                                    "error_ext": [{
                                        "field": "",
                                        "error_code": 0,
                                        "message": u"Failed to render document %s" % doc_type
                                    }]
                                }
                            sqldb.session.commit()

                            return False
                    failed_doc_types.add(doc_type)

                if not render_only_failed_docs:
                    batch_db_object.finalisation_count += 1
                    batch_db_object.status = BatchStatusEnum.BS_FINALISED
                    if batch_db_object.batch_rendering_start:
                        try:
                            dt = datetime.utcnow() - batch_db_object.batch_rendering_start
                            fs = dt.total_seconds() + dt.microseconds / 1000000.
                            zabbix_sender.send('celery_max_time', fs)
                        except Exception:
                            pass
                    batch_db_object.finalisation_date = datetime.utcnow()
                    CeleryScheduler.remove("not_finalised_check_and_send%s" % str(batch_db_object_id))
                    try:
                        if batch_db_object.batch_rendering_start:
                            dt = datetime.utcnow() - batch_db_object.batch_rendering_start
                            seconds = dt.total_seconds()
                            zabbix_sender.send("celery_max_time", seconds)
                    except Exception:
                        pass
                sqldb.session.commit()

                if has_errors:
                    if len(failed_doc_types) == 1 and failed_doc_types.pop() in ('reg_fee_invoice', 'ip_reg_fee_invoice'):
                        from services.ifns import ifns_manager
                        if ifns_manager.if_gp_pay_working():
                            logger.error(u"Invalid fee invoice render attempt (service.nalog.ru is working). Cancelling!")
                            batch_db_object.status = BatchStatusEnum.BS_EDITED
                            sqldb.session.commit()
                            return False
                    async_result = render_batch.apply_async((batch_db_object_id,), {'render_only_failed_docs': True}, countdown=300)
                    if not async_result.ready():
                        task_file.unbind = True
                        new_task_id = unicode(async_result.id)
                        batch_db_object.current_task_id = new_task_id
                        batch_db_object.batch_rendering_start = datetime.utcnow()
                        logger.debug(u"Task id: %s" % new_task_id)
                        sqldb.session.commit()
            except Exception:
                logger.exception(u"Failed to render batch %s" % batch_db_object_id)
                if not render_only_failed_docs:
                    batch_db_object.status = BatchStatusEnum.BS_EDITED
                    sqldb.session.commit()

        if render_only_failed_docs and batch_db_object.paid:
            user = batch_db_object._owner
            addr_to = user.email or ""
            if not addr_to:
                logger.warning(u"Failed to send email: user %s has no email" % unicode(user.id))
            else:
                documents = BatchManager.get_shared_links_to_rendered_docs(batch_db_object, config, logger)

                if batch_db_object.batch_type == DocumentBatchTypeEnum.DBT_NEW_LLC:
                    go_further_url = u"%s://%s/ooo/?id=%s" % (
                        config['WEB_SCHEMA'], config['DOMAIN'], batch_db_object_id)
                    go_further_url = utm_args(go_further_url, 'deferred_docs_ready', user.id) + u"#page=documents"
                    go_further_url = UserManager.make_auth_url(go_further_url, user).get_url(config)

                    short_name = batch_db_object.data.get('short_name', "")
                    send_email.send_email.delay(addr_to, "deferred_docs_ready",
                                                go_further_url=go_further_url,
                                                short_name=short_name,
                                                schema=config['WEB_SCHEMA'],
                                                domain=config['DOMAIN'],
                                                docs=documents,
                                                user_id=str(user.id)
                                                )
                elif batch_db_object.batch_type == DocumentBatchTypeEnum.DBT_NEW_IP:
                    go_further_url = u"%s://%s/ip/?id=%s" % (
                        config['WEB_SCHEMA'], config['DOMAIN'], batch_db_object_id)
                    go_further_url = utm_args(go_further_url, 'deferred_ip_docs_ready', user.id) + u"#page=documents"
                    go_further_url = UserManager.make_auth_url(go_further_url, user).get_url(config)
                    short_name = ""
                    try:
                        pp_data = batch_db_object.data.get('person')
                        if pp_data and '_id' in pp_data:
                            person_db = PrivatePersonDbObject.query.filter_by(id=pp_data['_id']).scalar()
                            if person_db:
                                person = PrivatePerson.db_obj_to_field(person_db)
                                short_name = person.get_short_name()
                    except Exception:
                        logger.exception(u"Failed to get batch caption")

                    send_email.send_email.delay(addr_to, "deferred_ip_docs_ready",
                                                go_further_url=go_further_url,
                                                short_name=short_name,
                                                schema=config['WEB_SCHEMA'],
                                                domain=config['DOMAIN'],
                                                docs=documents,
                                                user_id=str(user.id)
                                                )

    return True
Exemple #17
0

load_filters(app.jinja_env, app.config)
set_template_loader(app.jinja_env)

init_blueprints(app)
init_services(app)
init_sql_db(app)
init_plugins()
init_flask_signals()

#noinspection PyUnresolvedReferences
init_login_system(app, app.config)
app.secret_key = app.config['secret_key']
from fw.auth.user_manager import UserManager
UserManager.init(app.config, app.logger)


@app.errorhandler(413)
def catcher(error):
    data_json = json.dumps(
        {"error": {"code": errors.FileToLarge.ERROR_CODE, "message": errors.FileToLarge.ERROR_MESSAGE}})
    result = Response(data_json, mimetype='application/json', status=400)
    result.headers.add('Access-Control-Allow-Credentials', "true")
    result.headers.add('Access-Control-Allow-Origin', "http://%s" % app.config['site_domain'])
    return result


@app.context_processor
def inject_user():
    return dict(js_scripts_suffix=u".min" if not app.production else u"")
Exemple #18
0
def make_auth_url(val, user_uuid):
    from fw.auth.user_manager import UserManager, AuthUser
    user = AuthUser.query.filter_by(uuid=user_uuid).scalar()
    if not user:
        return val  # fallback
    return UserManager.make_auth_url(val, user)
def make_auth_url(val, user_uuid):
    from fw.auth.user_manager import UserManager, AuthUser
    user = AuthUser.query.filter_by(uuid=user_uuid).scalar()
    if not user:
        return val   # fallback
    return UserManager.make_auth_url(val, user)
Exemple #20
0
def signup(email=None, access_token=None, password=None, social_network=None):
    if "X-Forwarded-For" in request.headers and request.headers.getlist("X-Forwarded-For"):
        ip = request.headers.getlist("X-Forwarded-For")[0]
    elif "X-Real-Ip" in request.headers and request.headers.getlist("X-Real-Ip"):
        ip = request.headers.getlist("X-Real-Ip")[0]
    else:
        ip = request.remote_addr

    if ip in current_app.config['OFFICE_IP']:
        is_test_user = True
    else:
        is_test_user = False

    if not email and not access_token:
        raise errors.MissingRequiredParameter('email')

    if not EmailAddressValidator().validate(email) and not access_token:
        raise errors.InvalidParameterValue('email')

    if access_token:
        password = ''

    if social_network and social_network not in SocialServiceEnum.TAG_ALL:
        raise errors.InvalidParameterValue('social_network')

    if not PasswordValidator().validate(password) and not access_token:
        raise errors.MissingRequiredParameter('password')

    if current_user and not current_user.is_anonymous:
        if not current_user.temporal:
            raise errors.InvalidParameterValue('email')

        new_user = UserManager.promote_temp_user(current_user, access_token, None, email, u"", u"", u"", password, social_network)
        new_user.is_tester = is_test_user
    else:
        new_user = UserManager.register_user(access_token, None, email, u"", u"", u"", password, social_network)
        new_user.is_tester = is_test_user

    google_client_id = request.cookies.get('_ga_cid')
    if google_client_id and not new_user.temporal:
        metrics.update_user_info(new_user, google_client_id=google_client_id)

    new_user.email = new_user.email.lower() if new_user.email else u""

    data = get_user_api_structure(new_user)
    result = {"result": data}

    if not email and access_token:
        login_user(new_user)
        my_resp = MyResp()
        current_app.session_interface.save_session(current_app, flask.session, my_resp)
        return result

    user = UserManager.login_user(email, password)
    if user:
        login_user(user)
        my_resp = MyResp()
        current_app.session_interface.save_session(current_app, flask.session, my_resp)
        user.last_login_date = datetime.utcnow()

    return result
Exemple #21
0
def account_by_code(user_id=None, code=None):
    user = UserManager.get_user_by_code(user_id, code)

    data = get_user_api_structure(user)
    return {"result": data}
Exemple #22
0
def password_recovery(email=None, mobile=None):
    UserManager.send_password_recovery_code(email, mobile)
    return {"result": True}
Exemple #23
0
def update_profile(email=None, notifications=None, mobile=None):
    UserManager.update_profile(current_user, email, new_mobile=mobile)

    data = get_user_api_structure(current_user)
    return {"result": data}
Exemple #24
0
def login_external(social_network=None, next_page=""):
    class MyResp(Response):
        def set_cookie(self, key, value='', max_age=None, expires=None,
                       path='/', domain=None, secure=None, httponly=False):
            self.__name = key
            self.__val = value
            super(MyResp, self).set_cookie(key, value, max_age, expires, path, domain, secure, httponly)

    try:
        code = request.args['code']
    except Exception:
        if 'error' in request.args:
            html = u"""<html><head></head><body><script>window.location.href = "/";</script></body></html>"""
            my_resp = MyResp(html, status=200, content_type="text/html; charset=utf-8")
            return my_resp
        raise errors.InvalidParameterValue('code')

    if social_network not in ('facebook', 'vk', 'google'):
        raise errors.InvalidParameterValue('social_network')

    backend = SocialServiceBackends.backends.get(social_network)
    if not backend:
        raise errors.InvalidParameterValue('social_network')

    config = current_app.config

    if backend:
        if '?' in next_page:
            next_page = next_page.split('?')[0]
        current_app.logger.debug(u"2 redirect url: %s" % next_page)
        access_token, ext_data = backend.get_token(code, config, next_page=next_page)
        if not access_token:
            raise errors.SocialAuthError()

        user_data = backend.get_user_data(config, access_token)
        social_uid = user_data.get('id')
        if not social_uid:
            raise errors.SocialAuthError()
        social_service_user_link = backend.get_user_link(unicode(social_uid))
        if social_service_user_link:
            user = social_service_user_link.user
        else:
            ext_data = ext_data or {}
            if 'email' not in ext_data:
                ext_data = backend.get_user_data(config, access_token)
            user, user_profile = UserManager.create_user(access_token, "", ext_data.get('email', ""), "", "", "", "",
                                                            social_network, email_is_social=True)

        old_user_id = current_user.id if (
            current_user and not current_user.is_anonymous and current_user.temporal) else None
        if old_user_id:
            new_user_id = user.id
            change_account_data_owner(old_user_id, new_user_id)

        google_client_id = request.cookies.get('_ga_cid')
        if google_client_id and not user.temporal:
            metrics.update_user_info(user, google_client_id=google_client_id)
        login_user(user)
        user.last_login_date = datetime.utcnow()

        my_resp = MyResp()
        current_app.session_interface.save_session(current_app, flask.session, my_resp)
        # noinspection PyUnresolvedReferences
        html = u"""
        <html>
        <head></head>
        <body>
        <script>
        window.location.href = "/%s";
        </script>
        </body>
        </html>
    """ % next_page
        my_resp = MyResp(html, status=200, content_type="text/html; charset=utf-8")
        return my_resp

    return {"result": None}
Exemple #25
0
def resend_activation_code(email=None, mobile=None):
    UserManager.resend_activation_code(email, mobile)
    return {'result': True}
Exemple #26
0
def render_batch_raw(batch_db_object_id, render_only_failed_docs=False):
    request = current_task.request
    config = celery.conf.get('config')
    eager = celery.conf['CELERY_ALWAYS_EAGER']
    app = celery.conf['flask_app']()
    logger = app.logger

    from fw.documents.batch_manager import BatchManager
    with app.app_context():
        batch_db_object = DocumentBatchDbObject.query.filter_by(
            id=batch_db_object_id).first()
        if not batch_db_object:
            logger.error(
                u"Failed to find batch with id %s in collection %s in db %s" %
                (batch_db_object_id, DocumentBatchDbObject.COLLECTION_NAME,
                 config['db_name']))
            return False

        batch_db_object.current_task_id = request.id
        batch_db_object.batch_rendering_start = datetime.utcnow()
        sqldb.session.commit()

        task_holder = BatchTaskFileIdHolder(
            request.id, config,
            batch_db_object) if not eager else FakeTaskHolder()
        with task_holder as task_file:
            logger.info(u"Generating documents for batch %s" %
                        batch_db_object_id)

            try:
                batch_type = batch_db_object.batch_type

                batch_manager = BatchManager.init(batch_db_object)
                batch_descriptor = DocRequisitiesStorage.get_batch_descriptor(
                    batch_type)
                doc_types_allowed_to_deferred_rendering = batch_descriptor.get(
                    'deferred_render_docs', [])

                watermark = None if batch_db_object.paid else "notpaid_watermark.png"

                has_errors = False
                failed_doc_types = set()
                for doc in batch_db_object._documents:
                    # if not task_file.exists():
                    #     logger.warning(u"Task with id %s has been revoked" % request.id)
                    #     batch_db_object.status = BatchStatusEnum.BS_EDITED
                    #     sqldb.session.commit()
                    #     return True

                    doc_type = doc.document_type
                    if render_only_failed_docs and doc.status != UserDocumentStatus.DS_RENDERING_FAILED:
                        continue

                    render_doc_file = batch_type == DocumentBatchTypeEnum.DBT_NEW_LLC and batch_db_object.paid
                    if not render_single_document(
                            doc, batch_manager.get_title(doc_type), watermark,
                            config, logger, request.id, render_doc_file):
                        has_errors = True
                        if doc_type not in doc_types_allowed_to_deferred_rendering:
                            if not render_only_failed_docs:
                                batch_db_object.status = BatchStatusEnum.BS_EDITED
                                batch_db_object.error_info = {
                                    "error_ext": [{
                                        "field":
                                        "",
                                        "error_code":
                                        0,
                                        "message":
                                        u"Failed to render document %s" %
                                        doc_type
                                    }]
                                }
                            sqldb.session.commit()

                            return False
                    failed_doc_types.add(doc_type)

                if not render_only_failed_docs:
                    batch_db_object.finalisation_count += 1
                    batch_db_object.status = BatchStatusEnum.BS_FINALISED
                    if batch_db_object.batch_rendering_start:
                        try:
                            dt = datetime.utcnow(
                            ) - batch_db_object.batch_rendering_start
                            fs = dt.total_seconds(
                            ) + dt.microseconds / 1000000.
                            zabbix_sender.send('celery_max_time', fs)
                        except Exception:
                            pass
                    batch_db_object.finalisation_date = datetime.utcnow()
                    CeleryScheduler.remove("not_finalised_check_and_send%s" %
                                           str(batch_db_object_id))
                    try:
                        if batch_db_object.batch_rendering_start:
                            dt = datetime.utcnow(
                            ) - batch_db_object.batch_rendering_start
                            seconds = dt.total_seconds()
                            zabbix_sender.send("celery_max_time", seconds)
                    except Exception:
                        pass
                sqldb.session.commit()

                if has_errors:
                    if len(failed_doc_types) == 1 and failed_doc_types.pop(
                    ) in ('reg_fee_invoice', 'ip_reg_fee_invoice'):
                        from services.ifns import ifns_manager
                        if ifns_manager.if_gp_pay_working():
                            logger.error(
                                u"Invalid fee invoice render attempt (service.nalog.ru is working). Cancelling!"
                            )
                            batch_db_object.status = BatchStatusEnum.BS_EDITED
                            sqldb.session.commit()
                            return False
                    async_result = render_batch.apply_async(
                        (batch_db_object_id, ),
                        {'render_only_failed_docs': True},
                        countdown=300)
                    if not async_result.ready():
                        task_file.unbind = True
                        new_task_id = unicode(async_result.id)
                        batch_db_object.current_task_id = new_task_id
                        batch_db_object.batch_rendering_start = datetime.utcnow(
                        )
                        logger.debug(u"Task id: %s" % new_task_id)
                        sqldb.session.commit()
            except Exception:
                logger.exception(u"Failed to render batch %s" %
                                 batch_db_object_id)
                if not render_only_failed_docs:
                    batch_db_object.status = BatchStatusEnum.BS_EDITED
                    sqldb.session.commit()

        if render_only_failed_docs and batch_db_object.paid:
            user = batch_db_object._owner
            addr_to = user.email or ""
            if not addr_to:
                logger.warning(u"Failed to send email: user %s has no email" %
                               unicode(user.id))
            else:
                documents = BatchManager.get_shared_links_to_rendered_docs(
                    batch_db_object, config, logger)

                if batch_db_object.batch_type == DocumentBatchTypeEnum.DBT_NEW_LLC:
                    go_further_url = u"%s://%s/ooo/?id=%s" % (
                        config['WEB_SCHEMA'], config['DOMAIN'],
                        batch_db_object_id)
                    go_further_url = utm_args(go_further_url,
                                              'deferred_docs_ready',
                                              user.id) + u"#page=documents"
                    go_further_url = UserManager.make_auth_url(
                        go_further_url, user).get_url(config)

                    short_name = batch_db_object.data.get('short_name', "")
                    send_email.send_email.delay(addr_to,
                                                "deferred_docs_ready",
                                                go_further_url=go_further_url,
                                                short_name=short_name,
                                                schema=config['WEB_SCHEMA'],
                                                domain=config['DOMAIN'],
                                                docs=documents,
                                                user_id=str(user.id))
                elif batch_db_object.batch_type == DocumentBatchTypeEnum.DBT_NEW_IP:
                    go_further_url = u"%s://%s/ip/?id=%s" % (
                        config['WEB_SCHEMA'], config['DOMAIN'],
                        batch_db_object_id)
                    go_further_url = utm_args(go_further_url,
                                              'deferred_ip_docs_ready',
                                              user.id) + u"#page=documents"
                    go_further_url = UserManager.make_auth_url(
                        go_further_url, user).get_url(config)
                    short_name = ""
                    try:
                        pp_data = batch_db_object.data.get('person')
                        if pp_data and '_id' in pp_data:
                            person_db = PrivatePersonDbObject.query.filter_by(
                                id=pp_data['_id']).scalar()
                            if person_db:
                                person = PrivatePerson.db_obj_to_field(
                                    person_db)
                                short_name = person.get_short_name()
                    except Exception:
                        logger.exception(u"Failed to get batch caption")

                    send_email.send_email.delay(addr_to,
                                                "deferred_ip_docs_ready",
                                                go_further_url=go_further_url,
                                                short_name=short_name,
                                                schema=config['WEB_SCHEMA'],
                                                domain=config['DOMAIN'],
                                                docs=documents,
                                                user_id=str(user.id))

    return True
    def run(self):
        #        self.logger.info(u"Проверка статуса регистрации компаний")
        #        self.logger.info(u'=' * 50)

        is_production = not self.config['STAGING'] and not self.config['DEBUG']
        days_30 = timedelta(days=30)
        # get list of testers
        from services.ifns.data_model.models import IfnsBookingObject

        # and exclude their batches
        query = DocumentBatchDbObject.query.filter(
            DocumentBatchDbObject.status == BatchStatusEnum.BS_FINALISED,
            DocumentBatchDbObject.paid == True,
            DocumentBatchDbObject.finalisation_date >= datetime.now() - days_30
        )
        if is_production:
            query = query.join(AuthUser).filter(AuthUser.is_tester==False)

        skip_statuses = (IfnsRegStatusEnum.IRS_REGISTERED, IfnsRegStatusEnum.IRS_REGISTRATION_DECLINED)
        for batch in query:
            status = (batch.result_fields or {}).get('ifns_reg_info', {}).get('status', 'unknown')
            if status in skip_statuses:
                continue

            batch_id = batch.id
            # self.logger.info(u"%s" % unicode(batch_id))

            ifns = (batch.result_fields or {}).get('ifns', None)

            #self.logger.info(u"ifns: %s" % ifns)
            ifns_data = ifns_manager.get_ifns_data(ifns)
            if ifns_data and ifns_data.rou and 'code' in ifns_data.rou:
                ifns = ifns_data.rou['code']

            full_name = ""
            short_name = ""
            if batch.batch_type == DocumentBatchTypeEnum.DBT_NEW_LLC:
                full_name = batch.data.get('full_name', None)
                short_name = batch.data.get('short_name', None)
            elif batch.batch_type == DocumentBatchTypeEnum.DBT_NEW_IP:
                try:
                    reg_responsible_person = batch.data.get('person', None)
                    person_field = ObjectRefField()
                    person_field.parse_raw_value(reg_responsible_person, {}, api_data=False, update=False)
                    full_name = person_field.full_name
                    short_name = person_field.short_name
                except Exception:
                    self.logger.exception(u"Failed to parse IP person")
            else:
                self.logger.exception(u"Unknown batch type for batch %s" % str(batch['_id']))

            doc_rec_type = batch.data.get('obtain_way', None)
            application_form = batch.data.get('registration_way', None)
            if batch.batch_type == DocumentBatchTypeEnum.DBT_NEW_LLC:
                applicant_fio = u""
            elif batch.batch_type == DocumentBatchTypeEnum.DBT_NEW_IP:
                applicant_fio = full_name
            for doc in batch._documents:
                if doc.document_type == DocumentTypeEnum.DT_REGISTRATION_FEE_INVOICE:
                    founder_applicant = doc.data.get('founder_applicant', None)
                    if founder_applicant:
                        try:
                            founder_app_field = FounderObject()
                            founder_app_field.parse_raw_value(founder_applicant, {}, api_data=False, update=False)
                            applicant_fio = founder_app_field.full_name
                        except Exception:
                            self.logger.exception(u"Failed to parse founder object")
                    break

            if application_form == RegistrationWay.RW_RESPONSIBLE_PERSON:
                reg_responsible_person = batch.data.get('reg_responsible_person', None)
                if reg_responsible_person:
                    try:
                        reg_responsible_person_field = ObjectRefField()
                        reg_responsible_person_field.parse_raw_value(
                            reg_responsible_person, {}, api_data=False, update=False)
                        applicant_fio = reg_responsible_person_field.full_name
                    except Exception:
                        self.logger.exception(u"Failed to parse person")

            ifns_booking = IfnsBookingObject.query.filter_by(
                batch_id=batch_id,
                service_id=IfnsServiceEnum.IS_REG_COMPANY,
                _discarded=False
            ).first()
            if ifns_booking:
                dt = ifns_booking.date
                if dt and is_production and datetime.now() < dt:
                    self.logger.info(u"Too early - skip")
                    continue

            # self.logger.info(u"Checking batch %s" % unicode(batch_id))
            date_from = batch.finalisation_date - timedelta(days=5)
            date_to = date_from + timedelta(days=30)
            result = current_app.external_tools.get_ifns_registrations(
                full_name,
                date_from=date_from,
                date_to=date_to,
                ifns=ifns,
                service_nalog_ru_url=self.config['SERVICE_NALOG_RU_URL'],
                logger=self.logger) or []

            if not result:
                # self.logger.info(u"No reservations for batch %s" % unicode(batch_id))
                continue
            else:
                for item in result:
                    try:
                        self.logger.info(u"Found reservation info for batch %s (%s)" % (
                            batch_id,
                            json.dumps(item, default=lambda x: unicode(x))
                        ))
                        if 'status' not in item:
                            continue
                        status = item['status']
                        batch_result_fields = batch.result_fields or {}

                        if status == 'registered' and ('ogrn' in item or 'ogrnip' in item):
                            ogrn = item.get('ogrn')
                            ogrnip = item.get('ogrnip')
                            reg_date = None
                            try:
                                reg_date = item.get('reg_date', None)
                                if reg_date:
                                    reg_date = datetime.strptime(reg_date, "%d.%m.%Y")
                            except Exception:
                                self.logger.exception(u"Failed to convert reg_date")
                            reg_info = {
                                'status': 'registered',
                                'reg_date': reg_date,
                            }
                            if ogrn:
                                reg_info['ogrn'] = ogrn
                            elif ogrnip:
                                reg_info['ogrnip'] = ogrnip

                            booking = IfnsBookingObject.query.filter_by(
                                batch_id=batch_id,
                                service_id=IfnsServiceEnum.IS_REG_COMPANY,
                                _discarded=False
                            ).first()
                            if booking:
                                booking.reg_info = reg_info
                                sqldb.session.commit()

                            batch_result_fields['ifns_reg_info'] = {
                                'status': 'registered',
                                'reg_date': reg_date,
                                'full_name': full_name
                            }
                            if ogrn:
                                batch_result_fields['ifns_reg_info']['ogrn'] = ogrn
                            elif ogrnip:
                                batch_result_fields['ifns_reg_info']['ogrnip'] = ogrnip

                            DocumentBatchDbObject.query.filter_by(id=batch.id).update({
                                'result_fields': batch_result_fields
                            })
                            sqldb.session.commit()
                            recipient = batch._owner.email or u""
                            obtain_person_fio = u""
                            if not recipient:
                                self.logger.warn(
                                    u"Failed to send ifns reg notify to user %s - no email address" % batch._owner_id)
                            else:
                                docs_recipient_fio = ""
                                # Batch Type specific logic
                                if batch.batch_type == DocumentBatchTypeEnum.DBT_NEW_LLC:
                                    # TODO: This should be incapsulated
                                    if doc_rec_type == DocumentDeliveryTypeStrEnum.DDT_ISSUE_TO_THE_APPLICANT:
                                        doc = BatchDocumentDbObject.query.filter_by(batch=batch,
                                                                                    document_type=DocumentTypeEnum.DT_P11001).first()
                                        if doc:
                                            founders = doc.data['founders']
                                            for founder in founders:
                                                if founder.get('documents_recipient_type', '') != '':
                                                    person = founder.get('person', None)
                                                    if person and '_id' in person:
                                                        person_obj = PrivatePersonDbObject.query.filter_by(
                                                            id=person['_id']).scalar()
                                                        if person_obj:
                                                            pp = PrivatePerson.db_obj_to_field(person_obj)
                                                            if pp:
                                                                docs_recipient_fio = pp.full_name
                                                    else:
                                                        company = founder.get('company', None)
                                                        if company:
                                                            company_db_object = CompanyDbObject.query.filter_by(
                                                                id=company['_id']).scalar()
                                                            if company_db_object:
                                                                cc = CompanyObject.db_obj_to_field(company_db_object)
                                                                if cc and cc.general_manager and cc.general_manager.initialized:
                                                                    docs_recipient_fio = cc.general_manager.full_name
                                    elif doc_rec_type == DocumentDeliveryTypeStrEnum.DDT_ISSUE_TO_THE_APPLICANT_OR_AGENT:
                                        doc = BatchDocumentDbObject.query.filter_by(batch=batch,
                                                                                    document_type=DocumentTypeEnum.DT_DOVERENNOST_OBTAIN).first()

                                        if doc:
                                            doc_obtain_person = doc.data.get('doc_obtain_person', None)
                                            if doc_obtain_person and '_id' in doc_obtain_person:
                                                person_obj = PrivatePersonDbObject.query.filter_by(
                                                    id=doc_obtain_person['_id']).scalar()
                                                if person_obj:
                                                    pp = PrivatePerson.db_obj_to_field(person_obj)
                                                    if pp:
                                                        docs_recipient_fio = pp.full_name

                                        doc = BatchDocumentDbObject.query.filter_by(batch=batch,
                                                                                    document_type=DocumentTypeEnum.DT_P11001).first()
                                        if doc:
                                            founders = doc.data['founders']
                                            for founder in founders:
                                                if founder.get('documents_recipient_type', '') != '':
                                                    person = founder.get('person', None)
                                                    if person and '_id' in person:
                                                        person_obj = PrivatePersonDbObject.query.filter_by(
                                                            id=person['_id']).scalar()
                                                        if person_obj:
                                                            pp = PrivatePerson.db_obj_to_field(person_obj)
                                                            if pp:
                                                                obtain_person_fio = pp.full_name
                                                    else:
                                                        company = founder.get('company', None)
                                                        if company:
                                                            company_db_object = CompanyDbObject.query.filter_by(
                                                                id=company['_id']).scalar()
                                                            if company_db_object:
                                                                cc = CompanyObject.db_obj_to_field(company_db_object)
                                                                if cc and cc.general_manager and cc.general_manager.initialized:
                                                                    obtain_person_fio = cc.general_manager.full_name
                                    ifns_book_doc_receive_url = "%s://%s/ooo/?id=%s" % (self.config['WEB_SCHEMA'], self.config['DOMAIN'], unicode(batch_id))
                                    ifns_book_doc_receive_url = utm_args(ifns_book_doc_receive_url, "ifns_llc_reg_success", batch._owner_id) + u"#page=obtaining"
                                    ifns_book_doc_receive_url = UserManager.make_auth_url(ifns_book_doc_receive_url, batch._owner).get_url(self.config)

                                    send_email.send_email.delay(
                                        recipient,
                                        'ifns_llc_reg_success',
                                        short_name=short_name,
                                        doc_rec_by_email=(doc_rec_type == DocumentDeliveryTypeStrEnum.DDT_SEND_BY_MAIL),
                                        doc_rec_by_responsible=(
                                            doc_rec_type == DocumentDeliveryTypeStrEnum.DDT_ISSUE_TO_THE_APPLICANT_OR_AGENT),
                                        ifns_book_doc_receive_url=ifns_book_doc_receive_url,
                                        schema=self.config['WEB_SCHEMA'],
                                        domain=self.config['DOMAIN'],
                                        ogrn=ogrn,
                                        docs_ready_date=u"%d %s %s года" % (
                                            reg_date.day, get_russian_month_skl(reg_date.month), reg_date.year),
                                        docs_recipient_fio=docs_recipient_fio,
                                        obtain_person_fio=obtain_person_fio,
                                        service_startup=datetime.now() < datetime(2015, 6, 1),
                                        user_id=str(batch._owner_id)
                                    )
                                elif batch.batch_type == DocumentBatchTypeEnum.DBT_NEW_IP:

                                    if doc_rec_type == IPDocumentDeliveryTypeStrEnum.IP_DDT_RESPONSIBLE_PERSON:
                                        for doc in BatchDocumentDbObject.query.filter(
                                                        BatchDocumentDbObject.batch == batch,
                                                BatchDocumentDbObject.document_type.in_((
                                                        DocumentTypeEnum.DT_IP_DOV_FILING_RECEIVING_DOCS,
                                                        DocumentTypeEnum.DT_IP_DOV_RECEIVING_DOCS))):
                                            person = doc.data.get('ip_responsible_person', None)
                                            if person and '_id' in person:
                                                person_obj = PrivatePersonDbObject.query.filter_by(
                                                    id=person['_id']).scalar()
                                                if person_obj:
                                                    pp = PrivatePerson.db_obj_to_field(person_obj)
                                                    if pp:
                                                        docs_recipient_fio = pp.full_name
                                                        break

                                    ifns_book_doc_receive_url = "%s://%s/ip/?id=%s" % (self.config['WEB_SCHEMA'], self.config['DOMAIN'], batch_id)
                                    ifns_book_doc_receive_url = utm_args(ifns_book_doc_receive_url, 'ifns_ip_reg_success', batch._owner_id) + u"#page=obtaining"
                                    ifns_book_doc_receive_url = UserManager.make_auth_url(ifns_book_doc_receive_url, batch._owner).get_url(self.config)

                                    send_email.send_email.delay(
                                        recipient,
                                        'ifns_ip_reg_success',
                                        short_name=short_name,
                                        doc_rec_by_email=(doc_rec_type == IPDocumentDeliveryTypeStrEnum.IP_DDT_MAIL),
                                        doc_rec_by_responsible=(
                                            doc_rec_type == IPDocumentDeliveryTypeStrEnum.IP_DDT_RESPONSIBLE_PERSON),
                                        ifns_book_doc_receive_url=ifns_book_doc_receive_url,
                                        schema=self.config['WEB_SCHEMA'],
                                        domain=self.config['DOMAIN'],
                                        ogrnip=ogrnip,
                                        docs_ready_date=u"%d %s %s года" % (
                                            reg_date.day, get_russian_month_skl(reg_date.month), reg_date.year),
                                        docs_recipient_fio=docs_recipient_fio,
                                        obtain_person_fio=obtain_person_fio,
                                        service_startup=datetime.now() < datetime(2015, 6, 1),
                                        user_id=str(batch._owner_id)
                                    )
                            self.notify_admin(True, short_name, batch_id, application_form, doc_rec_type, applicant_fio,
                                              recipient, ogrn=ogrn, ogrnip=ogrnip, batch_type=batch.batch_type)
                        elif status == 'registration_declined':
                            reg_date = None
                            try:
                                reg_date = item.get('reg_date', None)
                                if reg_date:
                                    reg_date = datetime.strptime(reg_date, "%d.%m.%Y")
                            except Exception:
                                self.logger.exception(u"Failed to convert reg_date")

                            IfnsBookingObject.query.filter_by(
                                batch_id=batch_id,
                                service_id=IfnsServiceEnum.IS_REG_COMPANY,
                                _discarded=False).update({
                                    'reg_info': {
                                        'status': 'registration_declined',
                                        'reg_date': reg_date
                                    }
                                })
                            sqldb.session.commit()
                            batch_result_fields['ifns_reg_info'] = {
                                'status': 'registration_declined',
                                'reg_date': reg_date,
                                'full_name': full_name
                            }
                            recipient = batch._owner.email or u""
                            if not recipient:
                                self.logger.warn(
                                    u"Failed to send ifns reg notify to user %s - no email address" % batch._owner_id)
                            else:
                                if batch.batch_type == DocumentBatchTypeEnum.DBT_NEW_LLC:
                                    ifns_book_doc_receive_url = "%s://%s/ooo/?id=%s" % (self.config['WEB_SCHEMA'], self.config['DOMAIN'], batch_id)
                                    ifns_book_doc_receive_url = utm_args(ifns_book_doc_receive_url, 'ifns_llc_reg_fail', batch._owner_id) + u"#page=refusing"
                                    ifns_book_doc_receive_url = UserManager.make_auth_url(ifns_book_doc_receive_url, batch._owner).get_url(self.config)

                                    send_email.send_email.delay(
                                        recipient,
                                        'ifns_llc_reg_fail',
                                        short_name=short_name,
                                        doc_rec_by_email=(doc_rec_type == DocumentDeliveryTypeStrEnum.DDT_SEND_BY_MAIL),
                                        ifns_book_doc_receive_url=ifns_book_doc_receive_url,
                                        schema=self.config['WEB_SCHEMA'],
                                        domain=self.config['DOMAIN'],
                                        user_id=batch._owner_id
                                    )
                                elif batch.batch_type == DocumentBatchTypeEnum.DBT_NEW_IP:
                                    ifns_book_doc_receive_url = "%s://%s/ip/?id=%s" % (self.config['WEB_SCHEMA'], self.config['DOMAIN'], batch_id)
                                    ifns_book_doc_receive_url = utm_args(ifns_book_doc_receive_url, 'ifns_ip_reg_fail', batch._owner_id) + u"#page=refusing"
                                    ifns_book_doc_receive_url = UserManager.make_auth_url(ifns_book_doc_receive_url, batch._owner).get_url(self.config)
                                    send_email.send_email.delay(
                                        recipient,
                                        'ifns_ip_reg_fail',
                                        short_name=short_name,
                                        doc_rec_by_email=(doc_rec_type == IPDocumentDeliveryTypeStrEnum.IP_DDT_MAIL),
                                        ifns_book_doc_receive_url=ifns_book_doc_receive_url,
                                        schema=self.config['WEB_SCHEMA'],
                                        domain=self.config['DOMAIN'],
                                        user_id=batch._owner_id
                                    )
                            DocumentBatchDbObject.query.filter_by(id=batch.id).update({
                                'result_fields': batch_result_fields
                            })
                            sqldb.session.commit()
                            self.notify_admin(False, short_name, batch_id, application_form, doc_rec_type,
                                              applicant_fio, recipient, batch_type=batch.batch_type)
                        elif status == 'progress':
                            IfnsBookingObject.query.filter_by(
                                batch_id=batch_id,
                                service_id=IfnsServiceEnum.IS_REG_COMPANY,
                                _discarded=False
                            ).update({'reg_info': {
                                    'status': 'progress',
                                    'reg_date': item.get('reg_date', None)
                                }
                            })
                            batch_result_fields['ifns_reg_info'] = {
                                'status': 'progress',
                                'reg_date': item.get('reg_date', None),
                                'full_name': full_name
                            }
                            DocumentBatchDbObject.query.filter_by(id=batch.id).update({
                                'result_fields': batch_result_fields
                            })
                            sqldb.session.commit()
                        else:
                            raise Exception()

                        break
                    except Exception:
                        self.logger.exception(u"Failed to handle result")