コード例 #1
0
def create_person(person=None):
    try:
        person_doc = PrivatePerson.parse_raw_value(person, api_data=True)
        if not person_doc:
            raise Exception()
    except Exception, ex:
        raise errors.InvalidParameterValue('person')
コード例 #2
0
def update_person(person_id=None, person=None):
    person_db_obj = PrivatePersonDbObject.query.filter_by(id=unicode(person_id), _owner=current_user,
                                                          _batch=None).first()
    if not person_db_obj:
        raise errors.EntityNotFound()

    PrivatePerson.update_db_obj(person_db_obj, person, api_data=True)

    # validator = IsMyObjectVisitor(current_user._id) # todo:!!!
    # try:
    # validator.process(old_person_doc)
    # except NotMineException:
    # raise InvalidParameterValue('person')

    sqldb.session.commit()
    person_doc = PrivatePerson.db_obj_to_field(person_db_obj)
    return {"result": person_doc.get_api_structure()}
コード例 #3
0
    def get_batch_caption(self, batch_db):
        if not batch_db:
            return u""

        pp_data = batch_db.data.get('person')
        if pp_data and '_id' in pp_data:
            person_db = PrivatePersonDbObject.query.filter_by(id=pp_data['_id']).first()
            if person_db:
                person = PrivatePerson.db_obj_to_field(person_db)
                return u"Создание ИП «%s»" % person.get_short_name() if person else u"Создание ИП"

        return u"Создание ИП"
コード例 #4
0
    def get_batch_caption(self, batch_db):
        if not batch_db:
            return u""

        pp_data = batch_db.data.get('person')
        if pp_data and '_id' in pp_data:
            person_db = PrivatePersonDbObject.query.filter_by(
                id=pp_data['_id']).first()
            if person_db:
                person = PrivatePerson.db_obj_to_field(person_db)
                return u"Создание ИП «%s»" % person.get_short_name(
                ) if person else u"Создание ИП"

        return u"Создание ИП"
コード例 #5
0
def get_persons(person_id=None, count=None, offset=None):
    result_list = []
    person_id = str(person_id) if person_id else ''

    if person_id:
        person = PrivatePersonDbObject.query.filter_by(id=person_id, deleted=False, _owner=current_user,
                                                       _batch=None, _copy_id=None).first()
        if not person:
            raise errors.EntityNotFound('person_id')
        person_doc = PrivatePerson.db_obj_to_field(person)
        result_list.append(person_doc.get_api_structure())

        result_count = 1
        result_total = 1
    else:
        cur = PrivatePersonDbObject.query.filter_by(deleted=False, _owner=current_user, _batch=None, _copy_id=None).order_by(
            PrivatePersonDbObject.id.asc())
        result_total = cur.count()
        cur = PrivatePersonDbObject.query.filter_by(deleted=False, _owner=current_user, _batch=None, _copy_id=None).order_by(
            PrivatePersonDbObject.id.asc())

        if count is not None:
            cur = cur.limit(offset)
        if offset is not None:
            cur = cur.offset(offset)

        result_count = cur.count()
        for person in cur:
            person_doc = PrivatePerson.db_obj_to_field(person)
            result_list.append(person_doc.get_api_structure())

    return {'result': {
        'persons': result_list,
        'total': result_total,
        'count': result_count
    }}
コード例 #6
0
    def get_last_modified_batch_caption(self, batch_db):
        if not batch_db:
            return u""

        pp_data = batch_db.data.get('person')
        if pp_data and '_id' in pp_data:
            person_db = PrivatePersonDbObject.query.filter_by(id=pp_data['_id']).first()
            if person_db:
                person = PrivatePerson.db_obj_to_field(person_db)
                full_name_decl = declension(person.get_full_name(), 'gen')
                parts = full_name_decl.split(' ')
                if len(parts) in (2, 3):
                    surname_decl = parts[0].strip()
                    short_name = person.get_short_name()
                    parts = short_name.split(' ')
                    if len(parts) in (2, 3):
                        return surname_decl + u" " + u" ".join(parts[1:])
                return declension(person.get_short_name(), 'gen')

        return u""
コード例 #7
0
    def get_last_modified_batch_caption(self, batch_db):
        if not batch_db:
            return u""

        pp_data = batch_db.data.get('person')
        if pp_data and '_id' in pp_data:
            person_db = PrivatePersonDbObject.query.filter_by(
                id=pp_data['_id']).first()
            if person_db:
                person = PrivatePerson.db_obj_to_field(person_db)
                full_name_decl = declension(person.get_full_name(), 'gen')
                parts = full_name_decl.split(' ')
                if len(parts) in (2, 3):
                    surname_decl = parts[0].strip()
                    short_name = person.get_short_name()
                    parts = short_name.split(' ')
                    if len(parts) in (2, 3):
                        return surname_decl + u" " + u" ".join(parts[1:])
                return declension(person.get_short_name(), 'gen')

        return u""
コード例 #8
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
コード例 #9
0
    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")
コード例 #10
0
    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))
コード例 #11
0
ファイル: rendering.py プロジェクト: StanislavKraev/jb_code
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
コード例 #12
0
    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))
コード例 #13
0
    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")