Esempio n. 1
0
def batch_create(batch_type=None):
    try:
        DocRequisitiesStorage.get_batch_descriptor(batch_type)
    except Exception:
        raise errors.InvalidParameterValue('batch_type')

    batch_manager = BatchManager.init(batch_type=batch_type)
    new_batch = batch_manager.create_batch(current_user)
    sqldb.session.add(new_batch)
    sqldb.session.commit()
    doc_batch = DocumentBatch.db_obj_to_field(new_batch)
    return {'result': doc_batch.get_api_structure()}
Esempio n. 2
0
def batch_create(batch_type=None):
    try:
        DocRequisitiesStorage.get_batch_descriptor(batch_type)
    except Exception:
        raise errors.InvalidParameterValue('batch_type')

    batch_manager = BatchManager.init(batch_type=batch_type)
    new_batch = batch_manager.create_batch(current_user)
    sqldb.session.add(new_batch)
    sqldb.session.commit()
    doc_batch = DocumentBatch.db_obj_to_field(new_batch)
    return {'result': doc_batch.get_api_structure()}
Esempio n. 3
0
def _init_doc_requisities(config):
    from services.ip_reg.documents.initial_db_data_ip import load_data
    data = load_data(config)

    templates = (
        "P21001_TEMPLATE",
        "IP_DOV_FILING_TEMPLATE",
        "IP_DOV_RECEIVING_TEMPLATE",
        "IP_DOV_FILING_RECEIVING_TEMPLATE",
        "IP_LETTER_INVENTORY_TEMPLATE",
        "IP_USN_TEMPLATE",
        "IP_ESHN_TEMPLATE"
    )

    for template_name in templates:
        DocRequisitiesStorage.add_template(data[template_name]['doc_name'], data[template_name])

    schemas = (
        "P21001_SCHEMA",
        "IP_REG_BATCH_SCHEMA",
        "IP_STATE_DUTY_SCHEMA",
        "IP_DOV_FILING_SCHEMA",
        "IP_DOV_RECEIVING_SCHEMA",
        "IP_DOV_FILING_RECEIVING_SCHEMA",
        "IP_LETTER_INVENTORY_SCHEMA",
        "IP_USN_SCHEMA",
        "IP_ESHN_SCHEMA"
    )

    for schema_name in schemas:
        DocRequisitiesStorage.add_schema(data[schema_name]['doc_name'], data[schema_name])

    matchers = (
        "P21001_MATCHER",
        "IP_USN_MATCHER",
        "IP_ESHN_MATCHER"
    )

    for matcher_name in matchers:
        DocRequisitiesStorage.add_field_matcher(data[matcher_name]['doc_name'], data[matcher_name])

    bd = dict(
        batch_type=DocumentBatchTypeEnum.DBT_NEW_IP,
        doc_types=[
            DocumentTypeEnum.DT_P21001,
            DocumentTypeEnum.DT_IP_STATE_DUTY,
            DocumentTypeEnum.DT_IP_DOV_FILING_DOCS,
            DocumentTypeEnum.DT_IP_DOV_RECEIVING_DOCS,
            DocumentTypeEnum.DT_IP_DOV_FILING_RECEIVING_DOCS,
            DocumentTypeEnum.DT_IP_USN_CLAIM,
            DocumentTypeEnum.DT_IP_ESHN_CLAIM,
            DocumentTypeEnum.DT_IP_LETTER_INVENTORY
        ],
        result_fields=data['IP_REG_RESULT_FIELDS'],
        deferred_render_docs=data['IP_REG_DEFER_DOCS'],
        fields=data['IP_REG_BATCH_SCHEMA']["fields"]
    )

    DocRequisitiesStorage.add_batch_descriptor(DocumentBatchTypeEnum.DBT_NEW_IP, bd)
Esempio n. 4
0
def run_scheduled_task(descriptor_name, action_name, batch_id):
    app = celery.conf['flask_app']()
    with app.app_context():
        batch_db = DocumentBatchDbObject.query.filter_by(id=batch_id).scalar()
        descriptor = DocRequisitiesStorage.get_batch_descriptor(descriptor_name)
        action = descriptor['actions'][action_name]
        BatchManager.perform_action(action, batch_db, {}, app.logger, app.config)
Esempio n. 5
0
    def make_docs_from_batch_fields(self, field_set, current_batch_db_object=None):
        batch_descriptor = DocRequisitiesStorage.get_batch_descriptor(DocumentBatchTypeEnum.DBT_NEW_LLC)
        docs = []
        fields = field_set

        doc_in_batch = lambda doc_type_, batch_: any([doc_.document_type == doc_type_ for doc_ in batch_._documents])

        batch_doc_types = batch_descriptor.get('doc_types', [])
        for doc_type in batch_doc_types:
            if doc_type in self.THIRD_STAGE_DOCS and not doc_in_batch(doc_type, current_batch_db_object):
                continue

            result_fields = current_batch_db_object.result_fields or {}
            ifns_reg_status = result_fields.get('ifns_reg_info', {}).get('status', '')
            if ifns_reg_status == 'registered' and doc_type in self.FIRST_STAGE_DOCS:
                continue

            doc = self.get_doc_schema(doc_type)

            doc_data = doc
            new_doc = {
                "document_type": doc_data['doc_name'],
                "creation_date": datetime.utcnow(),
                "status": UserDocumentStatus.DS_NEW,
                "rendered_docs": []
            }
            data = transform_with_schema(fields, doc_data)

            if data is not None:
                user_doc = UserDocument.parse_raw_value(new_doc, api_data=False)
                user_doc.data.value = data
                user_doc.data.initialized = True
                docs.append(user_doc)

        return docs
Esempio n. 6
0
def run_scheduled_task(descriptor_name, action_name, batch_id):
    app = celery.conf['flask_app']()
    with app.app_context():
        batch_db = DocumentBatchDbObject.query.filter_by(id=batch_id).scalar()
        descriptor = DocRequisitiesStorage.get_batch_descriptor(
            descriptor_name)
        action = descriptor['actions'][action_name]
        BatchManager.perform_action(action, batch_db, {}, app.logger,
                                    app.config)
Esempio n. 7
0
def _init_doc_requisities(config):
    from services.osago.documents.initial_db_data import load_data
    data = load_data(config)

    templates = ("OSAGO_MAIL_LIST_TEMPLATE", "OSAGO_PRETENSION_TEMPLATE",
                 "OSAGO_DOCUMENTS_CLAIM_TEMPLATE",
                 "OSAGO_TRUST_SUBMISSION_DOCS_TEMPLATE",
                 "OSAGO_TRUST_OBTAIN_DOCS_TEMPLATE",
                 "OSAGO_TRUST_SUBMISION_OBTAIN_DOCS_TEMPLATE",
                 "OSAGO_CLAIM_COURT_ABSENT_TEMPLATE",
                 "OSAGO_CLAIM_ALL_EXECUTION_ACT_TEMPLATE",
                 "OSAGO_CLAIM_GUILTY_EXECUTION_ACT_TEMPLATE",
                 "OSAGO_CLAIM_INSURANCE_EXECUTION_ACT_TEMPLATE",
                 "OSAGO_LAWSUIT_TEMPLATE",
                 "OSAGO_OSAGO_COURT_MAIL_LIST_TEMPLATE")

    for template_name in templates:
        DocRequisitiesStorage.add_template(data[template_name]['doc_name'],
                                           data[template_name])

    schemas = ("OSAGO_SCHEMA", "OSAGO_MAIL_LIST_SCHEMA",
               "OSAGO_PRETENSION_SCHEMA", "OSAGO_DOCUMENTS_CLAIM_SCHEMA",
               "OSAGO_TRUST_SUBMISSION_DOCS_SCHEMA",
               "OSAGO_TRUST_OBTAIN_DOCS_SCHEMA",
               "OSAGO_TRUST_SUBMISION_OBTAIN_DOCS_SCHEMA",
               "OSAGO_CLAIM_COURT_ABSENT_SCHEMA",
               "OSAGO_CLAIM_ALL_EXECUTION_ACT_SCHEMA",
               "OSAGO_CLAIM_GUILTY_EXECUTION_ACT_SCHEMA",
               "OSAGO_CLAIM_INSURANCE_EXECUTION_ACT_SCHEMA",
               "OSAGO_LAWSUIT_SCHEMA", "OSAGO_OSAGO_COURT_MAIL_LIST_SCHEMA")

    for schema_name in schemas:
        DocRequisitiesStorage.add_schema(data[schema_name]['doc_name'],
                                         data[schema_name])

    bd = dict(batch_type=DocumentBatchTypeEnum.DBT_OSAGO,
              doc_types=[
                  DocumentTypeEnum.DT_OSAGO_MAIL_LIST,
                  DocumentTypeEnum.DT_OSAGO_PRETENSION,
                  DocumentTypeEnum.DT_OSAGO_DOCUMENTS_CLAIM,
                  DocumentTypeEnum.DT_OSAGO_TRUST_SUBMISSION_DOCS,
                  DocumentTypeEnum.DT_OSAGO_TRUST_OBTAIN_DOCS,
                  DocumentTypeEnum.DT_OSAGO_TRUST_SUBMISION_OBTAIN_DOCS,
                  DocumentTypeEnum.DT_OSAGO_CLAIM_COURT_ABSENT,
                  DocumentTypeEnum.DT_OSAGO_CLAIM_ALL_EXECUTION_ACT,
                  DocumentTypeEnum.DT_OSAGO_CLAIM_GUILTY_EXECUTION_ACT,
                  DocumentTypeEnum.DT_OSAGO_CLAIM_INSURANCE_EXECUTION_ACT,
                  DocumentTypeEnum.DT_OSAGO_LAWSUIT,
                  DocumentTypeEnum.DT_OSAGO_COURT_MAIL_LIST
              ],
              result_fields=data['OSAGO_RESULT_FIELDS'],
              fields=data['OSAGO_SCHEMA']['fields'],
              initial_status='pretension',
              actions=data['OSAGO_ACTIONS'],
              transitions=data['OSAGO_TRANSITIONS'],
              validation_condition=data['VALIDATION_CONDITION'],
              fixed_on_states=['generating_pretension', 'generating_claim'])

    DocRequisitiesStorage.add_batch_descriptor(DocumentBatchTypeEnum.DBT_OSAGO,
                                               bd)
Esempio n. 8
0
def _init_doc_requisities(config):
    from services.test_svc.documents.db_data import load_data
    data = load_data(config)

    templates = (
        "TEST_DOC_1_TEMPLATE",
        "TEST_DOC_2_TEMPLATE",
        "TEST_DOC_3_TEMPLATE",
    )

    for template_name in templates:
        DocRequisitiesStorage.add_template(data[template_name]['doc_name'], data[template_name])

    schemas = (
        "TEST_BATCH_SCHEMA",
        "TEST_DOC_3_SCHEMA",
        "TEST_DOC_2_SCHEMA",
        "TEST_DOC_1_SCHEMA"
    )

    for schema_name in schemas:
        DocRequisitiesStorage.add_schema(data[schema_name]['doc_name'], data[schema_name])

    matchers = (
        "TEST_DOC_1_MATCHER",
    )

    for matcher_name in matchers:
        DocRequisitiesStorage.add_field_matcher(data[matcher_name]['doc_name'], data[matcher_name])

    bd = dict(
        batch_type=DocumentBatchTypeEnum.DBT_TEST_TYPE,
        doc_types=[
            DocumentTypeEnum.DT_TEST_DOC_1,
            DocumentTypeEnum.DT_TEST_DOC_2,
            DocumentTypeEnum.DT_TEST_DOC_3
        ],
        result_fields=data['TEST_BATCH_RESULT_FIELDS'],
        deferred_render_docs=data['TEST_BATCH_DEFER_DOCS'],
        transitions=data['TEST_BATCH_TRANSITIONS'],
        actions=data['TEST_BATCH_ACTIONS'],
        initial_status="new",
        statuses=["new", "finalisation", "finalised", "edited"],
        fields=data["TEST_BATCH_SCHEMA"]['fields']
    )

    DocRequisitiesStorage.add_batch_descriptor(DocumentBatchTypeEnum.DBT_TEST_TYPE, bd)
    def test_async_render_empty_r11001(self):
        DocRequisitiesStorage.get_batch_descriptor(DocumentBatchTypeEnum.DBT_NEW_LLC)['doc_types'] = [DocumentTypeEnum.DT_P11001]

        with self.app.app_context():
            batch = DocumentBatchDbObject(
                batch_type=DocumentBatchTypeEnum.DBT_NEW_LLC,
                status=BatchStatusEnum.BS_NEW,
                _documents=[],
                data={},
                _owner=self.user._id
            )
            batch_id = batch.insert(self.db)

            new_batch_db_object = DocumentBatchDbObject(
                data={},
                batch_type=DocumentBatchTypeEnum.DBT_NEW_LLC
            )

            batch = DocumentBatch.parse_raw_value(new_batch_db_object.as_dict(), False)
            structure = batch.get_api_structure()
            del structure['batch_type']
            batch_json = json.dumps(structure)
            result = self.test_client.post('/batch/update/', data={
                'batch_id': unicode(batch_id),
                'batch': batch_json
            })
            self.assertEqual(result.status_code, 200)

            db_batch = DocumentBatchDbObject.query.filter_by(id=batch_id).first()
            new_user_doc_id = db_batch._documents[0].id
            result = self.test_client.get(
                '/batch/document/state/?batch_id=%s&document_id=%s' % (batch_id, new_user_doc_id))
            self.assertEqual(result.status_code, 200)
            result_data = json.loads(result.data)
            del result_data['result']['document_id']
            self.assertEqual(result_data, {u'result': {u'state': u'new', u'links': {u'pdf': None, u'jpeg': []}}})

            result = self.test_client.post('/batch/document/render/',
                                           data={'batch_id': unicode(batch_id), 'document_id': new_user_doc_id})
            self.assertEqual(result.status_code, 200)
            result_data = json.loads(result.data)
            self.assertEqual(result_data, {u'result': True})

            result = self.test_client.get(
                '/batch/document/state/?batch_id=%s&document_id=%s' % (batch_id, new_user_doc_id))
            self.assertEqual(result.status_code, 200)
            result_data = json.loads(result.data)
            self.assertEqual(result_data['result']['state'], 'rendered')
            self.assertTrue(result_data['result']['links']['pdf'].startswith(u'http://service.zz/storage/'))
Esempio n. 10
0
def _init_doc_requisities(config):
    from services.ip_reg.documents.initial_db_data_ip import load_data
    data = load_data(config)

    templates = ("P21001_TEMPLATE", "IP_DOV_FILING_TEMPLATE",
                 "IP_DOV_RECEIVING_TEMPLATE",
                 "IP_DOV_FILING_RECEIVING_TEMPLATE",
                 "IP_LETTER_INVENTORY_TEMPLATE", "IP_USN_TEMPLATE",
                 "IP_ESHN_TEMPLATE")

    for template_name in templates:
        DocRequisitiesStorage.add_template(data[template_name]['doc_name'],
                                           data[template_name])

    schemas = ("P21001_SCHEMA", "IP_REG_BATCH_SCHEMA", "IP_STATE_DUTY_SCHEMA",
               "IP_DOV_FILING_SCHEMA", "IP_DOV_RECEIVING_SCHEMA",
               "IP_DOV_FILING_RECEIVING_SCHEMA", "IP_LETTER_INVENTORY_SCHEMA",
               "IP_USN_SCHEMA", "IP_ESHN_SCHEMA")

    for schema_name in schemas:
        DocRequisitiesStorage.add_schema(data[schema_name]['doc_name'],
                                         data[schema_name])

    matchers = ("P21001_MATCHER", "IP_USN_MATCHER", "IP_ESHN_MATCHER")

    for matcher_name in matchers:
        DocRequisitiesStorage.add_field_matcher(data[matcher_name]['doc_name'],
                                                data[matcher_name])

    bd = dict(batch_type=DocumentBatchTypeEnum.DBT_NEW_IP,
              doc_types=[
                  DocumentTypeEnum.DT_P21001,
                  DocumentTypeEnum.DT_IP_STATE_DUTY,
                  DocumentTypeEnum.DT_IP_DOV_FILING_DOCS,
                  DocumentTypeEnum.DT_IP_DOV_RECEIVING_DOCS,
                  DocumentTypeEnum.DT_IP_DOV_FILING_RECEIVING_DOCS,
                  DocumentTypeEnum.DT_IP_USN_CLAIM,
                  DocumentTypeEnum.DT_IP_ESHN_CLAIM,
                  DocumentTypeEnum.DT_IP_LETTER_INVENTORY
              ],
              result_fields=data['IP_REG_RESULT_FIELDS'],
              deferred_render_docs=data['IP_REG_DEFER_DOCS'],
              fields=data['IP_REG_BATCH_SCHEMA']["fields"])

    DocRequisitiesStorage.add_batch_descriptor(
        DocumentBatchTypeEnum.DBT_NEW_IP, bd)
Esempio n. 11
0
def _init_doc_requisities(config):
    from services.test_svc.documents.db_data import load_data
    data = load_data(config)

    templates = (
        "TEST_DOC_1_TEMPLATE",
        "TEST_DOC_2_TEMPLATE",
        "TEST_DOC_3_TEMPLATE",
    )

    for template_name in templates:
        DocRequisitiesStorage.add_template(data[template_name]['doc_name'],
                                           data[template_name])

    schemas = ("TEST_BATCH_SCHEMA", "TEST_DOC_3_SCHEMA", "TEST_DOC_2_SCHEMA",
               "TEST_DOC_1_SCHEMA")

    for schema_name in schemas:
        DocRequisitiesStorage.add_schema(data[schema_name]['doc_name'],
                                         data[schema_name])

    matchers = ("TEST_DOC_1_MATCHER", )

    for matcher_name in matchers:
        DocRequisitiesStorage.add_field_matcher(data[matcher_name]['doc_name'],
                                                data[matcher_name])

    bd = dict(batch_type=DocumentBatchTypeEnum.DBT_TEST_TYPE,
              doc_types=[
                  DocumentTypeEnum.DT_TEST_DOC_1,
                  DocumentTypeEnum.DT_TEST_DOC_2,
                  DocumentTypeEnum.DT_TEST_DOC_3
              ],
              result_fields=data['TEST_BATCH_RESULT_FIELDS'],
              deferred_render_docs=data['TEST_BATCH_DEFER_DOCS'],
              transitions=data['TEST_BATCH_TRANSITIONS'],
              actions=data['TEST_BATCH_ACTIONS'],
              initial_status="new",
              statuses=["new", "finalisation", "finalised", "edited"],
              fields=data["TEST_BATCH_SCHEMA"]['fields'])

    DocRequisitiesStorage.add_batch_descriptor(
        DocumentBatchTypeEnum.DBT_TEST_TYPE, bd)
Esempio n. 12
0
    def merge_docs(self, batch_status, current_docs_db_models, new_docs_db_models, changed_field_names):
        merged_docs = []
        unused_docs = []

        if batch_status != BatchStatusEnum.BS_FINALISED:
            return new_docs_db_models, current_docs_db_models

        doc_fields_map = {}
        for doc in current_docs_db_models:
            doc_type = doc.document_type
            ds = DocRequisitiesStorage.get_schema(doc_type)
            doc_fields_map[doc_type] = set([f['name'] for f in ds['fields']]) #set(doc.data.keys())

        modified_doc_types_set = set()
        for field_name in changed_field_names:
            for cur_doc_type in doc_fields_map:
                if field_name in doc_fields_map[cur_doc_type]:
                    modified_doc_types_set.add(cur_doc_type)

        added_doc_types = set()
        for doc in current_docs_db_models:
            doc_type = doc.document_type
            if doc_type in LlcRegBatchManager.FIRST_STAGE_DOCS:
                merged_docs.append(doc)
                added_doc_types.add(doc_type)
            elif doc_type not in LlcRegBatchManager.FIRST_STAGE_DOCS and doc_type not in modified_doc_types_set:
                merged_docs.append(doc)
                added_doc_types.add(doc_type)

        for doc in new_docs_db_models:
            doc_type = doc.document_type

            if doc_type not in LlcRegBatchManager.FIRST_STAGE_DOCS and \
               doc.status != UserDocumentStatus.DS_RENDERED and doc_type not in added_doc_types:
                merged_docs.append(doc)

        for doc in current_docs_db_models:
            if doc.document_type not in added_doc_types:
                unused_docs.append(doc)

        return merged_docs, unused_docs
Esempio n. 13
0
def act(action, batch_db, previous_event_data, plugin_config, logger, config):
    assert batch_db
    if action != 'schedule':
        logger.error(u"Invalid action %s for task_scheduler plugin" % action)
        return False

    descriptor_name, task_to_schedule = plugin_config['action'].split('.')
    descriptor = DocRequisitiesStorage.get_batch_descriptor(descriptor_name)
    assert descriptor
    batch_actions = descriptor.get('actions') or {}
    if task_to_schedule not in batch_actions:
        logger.error(u"Invalid task name %s for task_scheduler plugin" % task_to_schedule)
        return False

    source_data = copy(plugin_config)
    source_data['<batch>'] = batch_db
    source_data['<app_config>'] = config
    source_data['<current_user>'] = batch_db._owner
    source_data['<previous_event_data>'] = previous_event_data

    task_id = plugin_config.get('task_id', None)

    if task_id and isinstance(task_id, dict):
        task_id = transform_field_with_schema(source_data, task_id).db_value()

    dt_type = plugin_config['dt_type']

    event_data = {
        'task_to_schedule': task_to_schedule,
        'dt_type': dt_type,
        '<action_dt>': datetime.utcnow(),
    }

    if dt_type == 'exact_time_every_day':
        dt_format = plugin_config['dt_format']
        dt_exact_time = plugin_config['dt_exact_time']
        dt_time_zone_region = plugin_config.get('dt_time_zone_region', u'Москва')
        dt_not_earlier = plugin_config.get('dt_not_earlier', None)

        if dt_format and isinstance(dt_format, dict):
            dt_format = transform_field_with_schema(source_data, dt_format).db_value()
        if dt_exact_time and isinstance(dt_exact_time, dict):
            dt_exact_time = transform_field_with_schema(source_data, dt_exact_time).db_value()
        if dt_time_zone_region and isinstance(dt_time_zone_region, dict):
            dt_time_zone_region = transform_field_with_schema(source_data, dt_time_zone_region)
            if dt_time_zone_region:
                dt_time_zone_region = dt_time_zone_region.db_value()
        if dt_not_earlier and isinstance(dt_not_earlier, dict):
            dt_not_earlier = transform_field_with_schema(source_data, dt_not_earlier).db_value()

        tz_name = RFRegionsEnum.get_time_zone(dt_time_zone_region) or "Europe/Moscow"
        now = datetime.utcnow()
        dt = calc_fixed_time_not_earlier(now, dt_exact_time, dt_not_earlier - now, tz_name)

        event_data.update({
            'dt': dt,
            'dt_format': dt_format,
            'dt_time_zone_region': dt_time_zone_region,
            'dt_not_earlier': dt_not_earlier,
            'tz_name': tz_name
        })
    else:
        raise NotImplementedError()

    try:
        new_task = CeleryScheduler.post('fw.async_tasks.scheduler.run_scheduled_task', eta=dt, args=(descriptor_name, task_to_schedule, batch_db.id),
                                        task_id=task_id, force_replace_task=True)
        event_data['task_id'] = new_task.id
    except Exception:
        logger.exception(u"Failed to schedule task")
        return False
    return True
Esempio n. 14
0
    def test_request_bank_via_web(self):
        with self.app.app_context():
            DocRequisitiesStorage.get_batch_descriptor(DocumentBatchTypeEnum.DBT_NEW_LLC)['doc_types'] = [
                DocumentTypeEnum.DT_P11001]

            general_manager_person = self.create_person(self.user)
            batch = self.create_batch(DocumentBatchTypeEnum.DBT_NEW_LLC, self.user)
            batch.data = {
                u"full_name": u"фывафыва",
                u"short_name": u"Бокс",
                u"address": {
                    "street_type": u"ул",
                    "index": 191186,
                    "house": u"4",
                    "region": u"Санкт-Петербург",
                    "flat": u"12",
                    "street": u"Большая Морская",
                    "address_string": u"г Санкт-Петербург, ул Большая Морская, д 4, кв 12",
                    "flat_type": u"кв",
                    "house_type": u"д",
                    "long_form_mode": True,
                    "ifns": u"7841",
                    "okato": u"92401385000",
                },
                u"address_type": u"general_manager_registration_address",
                u"general_manager_caption": u"повелитель",
                u"general_manager": {
                    "_id": general_manager_person.id,
                    "type": u"person"
                }
            }
            batch.result_fields = {
                'ifns_reg_info': {
                    'status': 'registered',
                    'reg_date': datetime.now(),
                    'full_name': u"Лютик",
                    'ogrn': 1095543023135
                }
            }
            sqldb.session.commit()
            batch_id = batch.id

            new_partner = BankPartnersObject(
                id=str(ObjectId("55c9afab543ed837fea53db2")),
                region=[RFRegionsEnum.RFR_SPB],
                city=[RFRegionsEnum.RFR_SPB],
                enabled=True,
                sort_index=10,
                link=u'',
                banner=u"some link",
                title=u'«Альфа-банк»',
                conditions=[
                    u"бесплатный выезд менеджера в офис",
                    u"открытие расчетного счета за 2‒3 дня",
                    u"3 месяца бесплатно при оплате сразу 9 месяцев",
                    u"до 3000 рублей на поиск профессионалов на HH.ru",
                    u"до 9000 рублей на Яндекс.Директ после открытия счета в подарок"
                ]
            )
            sqldb.session.add(new_partner)
            sqldb.session.commit()
            bank_id = new_partner.id

            svc = BankPartnersServiceObject(
                id=str(ObjectId()),
                type='web',
                config={
                    'method': 'post',
                    'url': 'http://ya.ru',
                },
                fields=partners_manage_commands._BANK_PARTNER_SCHEMA2,
                template_name='alpha_bank_web_request',
                bank_partner_id=bank_id
            )
            sqldb.session.add(svc)
            sqldb.session.commit()

            result = self.test_client.post('/partners/banks/send/', data={
                'batch_id': batch_id,
                'bank_id': bank_id,
                'bank_contact_phone': "+79001231213",
                'bank_contact_phone_general_manager': True,
                'send_private_data': True
            })
            self.assertEqual(result.status_code, 200)
            data = json.loads(result.data)
            batch = data['result']

            req_col = self.db['bank_partners_request']
            # DocumentBatchDbObject.get_collection(self.db).update({'_id': batch_id}, {
            #     '$set': {
            #         'data.ogrn': 1095543023135
            #     }
            # })
            # result = self.test_client.post('/partners/banks/send/', data={
            #     'batch_id': batch_id,
            #     'bank_id': bank_id,
            #     'bank_contact_phone_general_manager': True,
            #     'bank_contact_phone': "+79001231213",
            #     'send_private_data': True
            # })
            # self.assertEqual(result.status_code, 200)
            data = json.loads(result.data)
            batch = data['result']

            self.assertNotIn('error_info', batch)
            self.assertIn('result_fields', batch)

            result_fields = batch['result_fields']
            self.assertIn('bank_partner_requests', result_fields)
            self.maxDiff = None
            del result_fields['bank_partner_requests'][0]['sent_date']
            self.assertEqual(result_fields['bank_partner_requests'], [{
                'bank_partner_id': str(bank_id),
                'bank_contact_phone': '+79001231213',
                'bank_contact_phone_general_manager': 'true',
                # идентификатор партнера по банковскому обслуживанию
                'bank_partner_caption': u'«Альфа-банк»',
                # название банка-партнера
                'send_private_data': True,
                # дата отправки заявки
            }])

            self.assertEqual(BankPartnerRequestObject.query.count(), 1)
            bank_request = BankPartnerRequestObject.query.first()
            bank_request = copy(bank_request.__dict__)
            del bank_request['id']
            del bank_request['sent_date']
            del bank_request['_sa_instance_state']
            self.maxDiff = None
            self.assertEqual(bank_request, {
                'bank_partner_id': bank_id,
                'bank_contact_phone': '+79001231213',
                'bank_contact_phone_general_manager': 'true',
                'batch_id': batch_id,
                'bank_partner_caption': u'«Альфа-банк»',
                'send_private_data': True,
                'status': 'failed'
            })
Esempio n. 15
0
    def test_request_bank(self):
        with self.app.app_context():
            DocRequisitiesStorage.get_batch_descriptor(DocumentBatchTypeEnum.DBT_NEW_LLC)['doc_types'] = [
                DocumentTypeEnum.DT_P11001]

            general_manager_person = self.create_person(self.user)
            batch = self.create_batch(DocumentBatchTypeEnum.DBT_NEW_LLC, self.user)
            batch.data = {
                u"full_name": u"фывафыва",
                u"short_name": u"Бокс",
                u"address": {
                    "street_type": u"ул",
                    "index": 191186,
                    "house": u"4",
                    "region": u"Санкт-Петербург",
                    "flat": u"12",
                    "street": u"Большая Морская",
                    "address_string": u"г Санкт-Петербург, ул Большая Морская, д 4, кв 12",
                    "flat_type": u"кв",
                    "house_type": u"д",
                    "long_form_mode": True,
                    "ifns": u"7841",
                    "okato": u"92401385000",
                },
                u"address_type": u"general_manager_registration_address",
                u"general_manager_caption": u"повелитель",
                u"general_manager": {
                    "_id": general_manager_person.id,
                    "type": u"person"
                }
            }
            batch.result_fields = {
                'ifns_reg_info': {
                    'status': 'registered',
                    'reg_date': datetime.now(),
                    'full_name': u"Лютик",
                    'ogrn': 1095543023135
                }
            }
            sqldb.session.commit()
            batch_id = batch.id

            new_partner = BankPartnersObject(
                id=str(ObjectId()),
                region=[RFRegionsEnum.RFR_SPB],
                city=[RFRegionsEnum.RFR_SPB],
                enabled=True,
                sort_index=10,
                link=u'http://ya.ru',
                banner=u'http://yastatic.net/morda-logo/i/logo.svg',
                title=u'Йандекс',
                conditions=[]
            )
            sqldb.session.add(new_partner)
            sqldb.session.commit()
            bank_id = new_partner.id

            svc = BankPartnersServiceObject(
                id=str(ObjectId()),
                type='email',
                email='test_email@test_domain.zz',
                fields=partners_manage_commands._BANK_PARTNER_SCHEMA,
                template_name='account_creation_consultation_request',
                bank_partner_id=bank_id
            )
            sqldb.session.add(svc)
            sqldb.session.commit()

            result = self.test_client.post('/partners/banks/send/', data={
                'batch_id': batch_id,
                'bank_id': bank_id,
                'bank_contact_phone_general_manager': True,
                'bank_contact_phone': "+79001231213",
                'send_private_data': True
            })
            self.assertEqual(result.status_code, 200)
            data = json.loads(result.data)
            batch = data['result']

            # DocumentBatchDbObject.get_collection(self.db).update({'_id': batch_id}, {
            #     '$set': {
            #         'data.ogrn': 1095543023135
            #     }
            # })
            # result = self.test_client.post('/partners/banks/send/', data={
            #     'batch_id': batch_id,
            #     'bank_id': bank_id,
            #     'bank_contact_phone_general_manager': True,
            #     'bank_contact_phone': "+79001231213",
            #     'send_private_data': True
            # })
            # self.assertEqual(result.status_code, 200)
            data = json.loads(result.data)
            batch = data['result']

            self.assertNotIn('error_info', batch)
            self.assertIn('result_fields', batch)

            result_fields = batch['result_fields']
            self.assertIn('bank_partner_requests', result_fields)
            self.maxDiff = None
            del result_fields['bank_partner_requests'][0]['sent_date']
            self.assertEqual(result_fields['bank_partner_requests'], [{
                'bank_partner_id': str(bank_id),
                'bank_contact_phone': '+79001231213',
                'bank_contact_phone_general_manager': True,
                # идентификатор партнера по банковскому обслуживанию
                'bank_partner_caption': u'Йандекс',
                # название банка-партнера
                'send_private_data': True
                # дата отправки заявки
            }])

            self.assertEqual(BankPartnerRequestObject.query.count(), 1)
            bank_request = BankPartnerRequestObject.query.first()
            bank_request = copy(bank_request.__dict__)
            del bank_request['id']
            del bank_request['sent_date']
            del bank_request['_sa_instance_state']
            self.maxDiff = None
            self.assertEqual(bank_request, {
                'bank_partner_id': bank_id,
                'bank_contact_phone': '+79001231213',
                'bank_contact_phone_general_manager': 'true',
                'batch_id': batch_id,
                'bank_partner_caption': u'Йандекс',
                'send_private_data': True,
                'status': 'success'
            })
Esempio n. 16
0
def _init_doc_requisities(config):
    from services.osago.documents.initial_db_data import load_data
    data = load_data(config)

    templates = (
        "OSAGO_MAIL_LIST_TEMPLATE",
        "OSAGO_PRETENSION_TEMPLATE",
        "OSAGO_DOCUMENTS_CLAIM_TEMPLATE",
        "OSAGO_TRUST_SUBMISSION_DOCS_TEMPLATE",
        "OSAGO_TRUST_OBTAIN_DOCS_TEMPLATE",
        "OSAGO_TRUST_SUBMISION_OBTAIN_DOCS_TEMPLATE",
        "OSAGO_CLAIM_COURT_ABSENT_TEMPLATE",
        "OSAGO_CLAIM_ALL_EXECUTION_ACT_TEMPLATE",
        "OSAGO_CLAIM_GUILTY_EXECUTION_ACT_TEMPLATE",
        "OSAGO_CLAIM_INSURANCE_EXECUTION_ACT_TEMPLATE",
        "OSAGO_LAWSUIT_TEMPLATE",
        "OSAGO_OSAGO_COURT_MAIL_LIST_TEMPLATE"
    )

    for template_name in templates:
        DocRequisitiesStorage.add_template(data[template_name]['doc_name'], data[template_name])

    schemas = (
        "OSAGO_SCHEMA",
        "OSAGO_MAIL_LIST_SCHEMA",
        "OSAGO_PRETENSION_SCHEMA",
        "OSAGO_DOCUMENTS_CLAIM_SCHEMA",
        "OSAGO_TRUST_SUBMISSION_DOCS_SCHEMA",
        "OSAGO_TRUST_OBTAIN_DOCS_SCHEMA",
        "OSAGO_TRUST_SUBMISION_OBTAIN_DOCS_SCHEMA",
        "OSAGO_CLAIM_COURT_ABSENT_SCHEMA",
        "OSAGO_CLAIM_ALL_EXECUTION_ACT_SCHEMA",
        "OSAGO_CLAIM_GUILTY_EXECUTION_ACT_SCHEMA",
        "OSAGO_CLAIM_INSURANCE_EXECUTION_ACT_SCHEMA",
        "OSAGO_LAWSUIT_SCHEMA",
        "OSAGO_OSAGO_COURT_MAIL_LIST_SCHEMA"
    )

    for schema_name in schemas:
        DocRequisitiesStorage.add_schema(data[schema_name]['doc_name'], data[schema_name])

    bd = dict(
        batch_type=DocumentBatchTypeEnum.DBT_OSAGO,
        doc_types=[
            DocumentTypeEnum.DT_OSAGO_MAIL_LIST,
            DocumentTypeEnum.DT_OSAGO_PRETENSION,
            DocumentTypeEnum.DT_OSAGO_DOCUMENTS_CLAIM,
            DocumentTypeEnum.DT_OSAGO_TRUST_SUBMISSION_DOCS,
            DocumentTypeEnum.DT_OSAGO_TRUST_OBTAIN_DOCS,
            DocumentTypeEnum.DT_OSAGO_TRUST_SUBMISION_OBTAIN_DOCS,

            DocumentTypeEnum.DT_OSAGO_CLAIM_COURT_ABSENT,
            DocumentTypeEnum.DT_OSAGO_CLAIM_ALL_EXECUTION_ACT,
            DocumentTypeEnum.DT_OSAGO_CLAIM_GUILTY_EXECUTION_ACT,
            DocumentTypeEnum.DT_OSAGO_CLAIM_INSURANCE_EXECUTION_ACT,
            DocumentTypeEnum.DT_OSAGO_LAWSUIT,
            DocumentTypeEnum.DT_OSAGO_COURT_MAIL_LIST
        ],
        result_fields=data['OSAGO_RESULT_FIELDS'],
        fields=data['OSAGO_SCHEMA']['fields'],
        initial_status='pretension',
        actions=data['OSAGO_ACTIONS'],
        transitions=data['OSAGO_TRANSITIONS'],
        validation_condition=data['VALIDATION_CONDITION'],
        fixed_on_states=['generating_pretension', 'generating_claim']
    )

    DocRequisitiesStorage.add_batch_descriptor(DocumentBatchTypeEnum.DBT_OSAGO, bd)
Esempio n. 17
0
def _init_doc_requisities(config):
    from services.llc_reg.documents.initial_db_data import load_data
    from services.llc_reg.documents.third_stage_llc_reg_initial_db_data import load_data as third_stage_load_data
    data = load_data(config)
    data.update(third_stage_load_data(config))

    templates = (
        "P11001_TEMPLATE", "ARTICLES_TEMPLATE", "ACT_TEMPLATE", "USN_TEMPLATE",
        "ESHN_TEMPLATE", "DECISION_TEMPLATE", "CONTRACT_TEMPLATE",
        "DOVERENNOST_TEMPLATE", "DOVERENNOST_OBTAIN_TEMPLATE",
        "PROTOCOL_TEMPLATE", "SOGLASIE_SOBSTVENNIKOV_TEMPLATE",
        "GARANT_LETTER_ARENDA_TEMPLATE", "GARANT_LETTER_SUBARENDA_TEMPLATE",
        "GENERAL_MANAGER_CONTRACT_TEMPLATE", "GENERAL_MANAGER_ORDER_TEMPLATE",
        "ACCOUNTANT_CONTRACT_TEMPLATE", "ACCOUNTANT_IMPOSITION_ORDER_TEMPLATE",
        "ACCOUNTANT_ORDER_TEMPLATE", "ROSSTAT_CLAIM_TEMPLATE",
        "FSS_CLAIM_TEMPLATE", "PFR_CLAIM_TEMPLATE", "FOUNDERS_LIST_TEMPLATE",
        "COMPANY_DETAILS_TEMPLATE")

    for template_name in templates:
        DocRequisitiesStorage.add_template(data[template_name]['doc_name'],
                                           data[template_name])

    schemas = ("P11001_SCHEMA", "ARTICLES_SCHEMA", "ACT_SCHEMA", "USN_SCHEMA",
               "ESHN_SCHEMA", "DECISION_SCHEMA", "PROTOCOL_SCHEMA",
               "CONTRACT_SCHEMA", "REG_FEE_INVOICE_SCHEMA",
               "DOVERENNOST_SCHEMA", "DOVERENNOST2_SCHEMA",
               "SOGLASIE_SOBSTVENNIKOV_SCHEMA", "GARANT_LETTER_ARENDA_SCHEMA",
               "GARANT_LETTER_SUBARENDA_SCHEMA", "LLC_REG_BATCH_SCHEMA",
               "OOO_BANK_PARTNER_APPLICATION_SCHEMA",
               "GENERAL_MANAGER_CONTRACT_SCHEMA",
               "GENERAL_MANAGER_ORDER_SCHEMA", "ACCOUNTANT_CONTRACT_SCHEMA",
               "ACCOUNTANT_IMPOSITION_ORDER_SCHEMA", "ACCOUNTANT_ORDER_SCHEMA",
               "ROSSTAT_CLAIM_SCHEMA", "FSS_CLAIM_SCHEMA", "PFR_CLAIM_SCHEMA",
               "FOUNDERS_LIST_SCHEMA", "COMPANY_DETAILS_SCHEMA")

    for schema_name in schemas:
        DocRequisitiesStorage.add_schema(data[schema_name]['doc_name'],
                                         data[schema_name])

    matchers = ("P11001_MATCHER", "USN_MATCHER", "ESHN_MATCHER",
                "ACCOUNTANT_ORDER_MATCHER")

    for matcher_name in matchers:
        DocRequisitiesStorage.add_field_matcher(data[matcher_name]['doc_name'],
                                                data[matcher_name])

    bd = dict(
        batch_type=DocumentBatchTypeEnum.DBT_NEW_LLC,
        doc_types=[
            DocumentTypeEnum.DT_P11001, DocumentTypeEnum.DT_ARTICLES,
            DocumentTypeEnum.DT_USN, DocumentTypeEnum.DT_DECISION,
            DocumentTypeEnum.DT_PROTOCOL, DocumentTypeEnum.DT_ESHN,
            DocumentTypeEnum.DT_CONTRACT,
            DocumentTypeEnum.DT_REGISTRATION_FEE_INVOICE,
            DocumentTypeEnum.DT_DOVERENNOST,
            DocumentTypeEnum.DT_DOVERENNOST_OBTAIN,
            DocumentTypeEnum.DT_SOGLASIE_SOBSTVENNIKOV,
            DocumentTypeEnum.DT_GARANT_LETTER_ARENDA,
            DocumentTypeEnum.DT_GARANT_LETTER_SUBARENDA,
            DocumentTypeEnum.DT_GENERAL_MANAGER_CONTRACT,
            DocumentTypeEnum.DT_GENERAL_MANAGER_ORDER,
            DocumentTypeEnum.DT_ACCOUNTANT_CONTRACT,
            DocumentTypeEnum.DT_ACCOUNTANT_IMPOSITION_ORDER,
            DocumentTypeEnum.DT_ACCOUNTANT_ORDER,
            DocumentTypeEnum.DT_ROSSTAT_CLAIM, DocumentTypeEnum.DT_FSS_CLAIM,
            DocumentTypeEnum.DT_PFR_CLAIM, DocumentTypeEnum.DT_FOUNDERS_LIST,
            DocumentTypeEnum.DT_COMPANY_DETAILS
        ],
        result_fields=data['LLC_REG_RESULT_FIELDS'],
        deferred_render_docs=data['LLC_REG_DEFER_DOCS'],
        fields=data['LLC_REG_BATCH_SCHEMA']['fields'])

    DocRequisitiesStorage.add_batch_descriptor(
        DocumentBatchTypeEnum.DBT_NEW_LLC, bd)
    def test_async_render_empty_protocol(self):
        DocRequisitiesStorage.get_batch_descriptor(DocumentBatchTypeEnum.DBT_NEW_LLC)['doc_types'] = [DocumentTypeEnum.DT_PROTOCOL]

        with self.app.app_context():
            batch = DocumentBatchDbObject(
                batch_type=DocumentBatchTypeEnum.DBT_NEW_LLC,
                status=BatchStatusEnum.BS_NEW,
                _documents=[],
                data={},
                _owner=self.user._id
            )
            batch_id = batch.insert(self.db)

            founder_otvetstvennyi = PrivatePersonDbObject(**{
                "_owner": self.user._id,
                "name": u"",
                "surname": u"",
                "patronymic": u"",
                "inn": "781108730780",
                "sex": "male",
                "birthdate": datetime.now() - timedelta(days=365 * 30),
                "birthplace": u"Россия, деревня Гадюкино",
                "passport": {
                    "document_type": PersonDocumentTypeEnum.PD_INTERNAL,
                    "series": u"1123",
                    "number": u"192837",
                    "issue_date": datetime.now() - timedelta(days=365 * 14),
                    "issue_depart": u"УМВД Гадюкинского района Гадюкинской области",
                    "depart_code": u"111987"
                },
                "ogrnip": "123456789012345",
                "address": {
                    "region": RFRegionsEnum.RFR_SPB,
                    "index": 198209,
                    "district_type": DistrictTypeEnum.DIT_DISTRICT,
                    "district": u"Пушкинский",
                    "city_type": CityTypeEnum.CIT_CITY,
                    "city": u"Гадюкино",
                    "village_type": VillageTypeEnum.VIT_HUTOR,
                    "village": u"близ Диканьки",
                    "street_type": StreetTypeEnum.STT_BOULEVARD,
                    "street": u"Мотоциклистов",
                    "house_type": HouseTypeEnum.HOT_HOUSE,
                    "house": "4",
                    "building_type": BuildingTypeEnum.BIT_HOUSING,
                    "building": "2",
                    "flat_type": FlatTypeEnum.FLT_OFFICE,
                    "flat": "705",
                },
                "caption": u"Сантехник",
                "phone": "+79210001122",
                "email": "*****@*****.**",
                "living_country_code": 3,
                "living_address": u"г. Санкт-Петербург, д. Гадюкино, бульвар Мотоциклистов казарма 4, кв. 705"
            })
            founder_otvetstvennyi.insert(self.db)

            company_founder = CompanyDbObject(**{
                "_owner": self.user._id,
                "ogrn": "1234567890123",
                "inn": "781108730780",
                "kpp": "999999999",
                "general_manager_caption": u"генеральный директор",
                "full_name": u"Том и Джери",
                "short_name": u"ТиД",
                "general_manager": {
                },
                "address": {
                    "region": RFRegionsEnum.RFR_SPB,
                    "index": 123131,
                    "street_type": StreetTypeEnum.STT_STREET,
                    "street": u"Седова",
                    "house_type": HouseTypeEnum.HOT_HOUSE,
                    "house": "2",
                    "flat_type": FlatTypeEnum.FLT_OFFICE,
                    "flat": "2",
                },
                "phone": "+7(812)1234567"
            })
            company_founder.insert(self.app.db)

            new_batch_db_object = DocumentBatchDbObject(
                data={
                    u"address_type": u"office_address",
                    u"founders": [
                        {
                            u"founder": {
                                u"_id": company_founder.id,
                                u"type": u"company"
                            },
                            u"nominal_capital": 12312.22,
                            u"share": 85
                        }, {
                            u"founder": {
                                u"_id": founder_otvetstvennyi.id,
                                u"type": u"person"
                            },
                            u"nominal_capital": 1500.5,
                            u"share": 15
                        }
                    ],
                },
                batch_type=DocumentBatchTypeEnum.DBT_NEW_LLC
            )

            batch = DocumentBatch.parse_raw_value(new_batch_db_object.as_dict(), False)
            structure = batch.get_api_structure()
            del structure['batch_type']
            batch_json = json.dumps(structure)
            result = self.test_client.post('/batch/update/', data={
                'batch_id': unicode(batch_id),
                'batch': batch_json
            })
            self.assertEqual(result.status_code, 200)

            db_batch = DocumentBatchDbObject.query.filter_by(id=batch_id).first()
            new_user_doc_id = db_batch._documents[0].id

            result = self.test_client.get(
                '/batch/document/state/?batch_id=%s&document_id=%s' % (batch_id, new_user_doc_id))
            self.assertEqual(result.status_code, 200)
            result_data = json.loads(result.data)
            del result_data['result']['document_id']
            self.assertEqual(result_data, {u'result': {u'state': u'new', u'links': {u'pdf': None, u'jpeg': []}}})

            result = self.test_client.post('/batch/document/render/',
                                           data={'batch_id': unicode(batch_id), 'document_id': unicode(new_user_doc_id)})
            self.assertEqual(result.status_code, 200)
            result_data = json.loads(result.data)
            self.assertEqual(result_data, {u'result': True})

            result = self.test_client.get(
                '/batch/document_preview/state/?batch_id=%s&document_id=%s' % (unicode(batch_id), unicode(new_user_doc_id)))
            self.assertEqual(result.status_code, 200)
            result_data = json.loads(result.data)
            self.assertEqual(result_data['result']['state'], 'rendered')
            self.assertTrue(result_data['result']['links']['pdf'].startswith(u'http://service.zz/storage/'))
Esempio n. 19
0
    def test_request_bank_via_web(self):
        with self.app.app_context():
            DocRequisitiesStorage.get_batch_descriptor(
                DocumentBatchTypeEnum.DBT_NEW_LLC)['doc_types'] = [
                    DocumentTypeEnum.DT_P11001
                ]

            general_manager_person = self.create_person(self.user)
            batch = self.create_batch(DocumentBatchTypeEnum.DBT_NEW_LLC,
                                      self.user)
            batch.data = {
                u"full_name": u"фывафыва",
                u"short_name": u"Бокс",
                u"address": {
                    "street_type": u"ул",
                    "index": 191186,
                    "house": u"4",
                    "region": u"Санкт-Петербург",
                    "flat": u"12",
                    "street": u"Большая Морская",
                    "address_string":
                    u"г Санкт-Петербург, ул Большая Морская, д 4, кв 12",
                    "flat_type": u"кв",
                    "house_type": u"д",
                    "long_form_mode": True,
                    "ifns": u"7841",
                    "okato": u"92401385000",
                },
                u"address_type": u"general_manager_registration_address",
                u"general_manager_caption": u"повелитель",
                u"general_manager": {
                    "_id": general_manager_person.id,
                    "type": u"person"
                }
            }
            batch.result_fields = {
                'ifns_reg_info': {
                    'status': 'registered',
                    'reg_date': datetime.now(),
                    'full_name': u"Лютик",
                    'ogrn': 1095543023135
                }
            }
            sqldb.session.commit()
            batch_id = batch.id

            new_partner = BankPartnersObject(
                id=str(ObjectId("55c9afab543ed837fea53db2")),
                region=[RFRegionsEnum.RFR_SPB],
                city=[RFRegionsEnum.RFR_SPB],
                enabled=True,
                sort_index=10,
                link=u'',
                banner=u"some link",
                title=u'«Альфа-банк»',
                conditions=[
                    u"бесплатный выезд менеджера в офис",
                    u"открытие расчетного счета за 2‒3 дня",
                    u"3 месяца бесплатно при оплате сразу 9 месяцев",
                    u"до 3000 рублей на поиск профессионалов на HH.ru",
                    u"до 9000 рублей на Яндекс.Директ после открытия счета в подарок"
                ])
            sqldb.session.add(new_partner)
            sqldb.session.commit()
            bank_id = new_partner.id

            svc = BankPartnersServiceObject(
                id=str(ObjectId()),
                type='web',
                config={
                    'method': 'post',
                    'url': 'http://ya.ru',
                },
                fields=partners_manage_commands._BANK_PARTNER_SCHEMA2,
                template_name='alpha_bank_web_request',
                bank_partner_id=bank_id)
            sqldb.session.add(svc)
            sqldb.session.commit()

            result = self.test_client.post(
                '/partners/banks/send/',
                data={
                    'batch_id': batch_id,
                    'bank_id': bank_id,
                    'bank_contact_phone': "+79001231213",
                    'bank_contact_phone_general_manager': True,
                    'send_private_data': True
                })
            self.assertEqual(result.status_code, 200)
            data = json.loads(result.data)
            batch = data['result']

            req_col = self.db['bank_partners_request']
            # DocumentBatchDbObject.get_collection(self.db).update({'_id': batch_id}, {
            #     '$set': {
            #         'data.ogrn': 1095543023135
            #     }
            # })
            # result = self.test_client.post('/partners/banks/send/', data={
            #     'batch_id': batch_id,
            #     'bank_id': bank_id,
            #     'bank_contact_phone_general_manager': True,
            #     'bank_contact_phone': "+79001231213",
            #     'send_private_data': True
            # })
            # self.assertEqual(result.status_code, 200)
            data = json.loads(result.data)
            batch = data['result']

            self.assertNotIn('error_info', batch)
            self.assertIn('result_fields', batch)

            result_fields = batch['result_fields']
            self.assertIn('bank_partner_requests', result_fields)
            self.maxDiff = None
            del result_fields['bank_partner_requests'][0]['sent_date']
            self.assertEqual(
                result_fields['bank_partner_requests'],
                [{
                    'bank_partner_id': str(bank_id),
                    'bank_contact_phone': '+79001231213',
                    'bank_contact_phone_general_manager': 'true',
                    # идентификатор партнера по банковскому обслуживанию
                    'bank_partner_caption': u'«Альфа-банк»',
                    # название банка-партнера
                    'send_private_data': True,
                    # дата отправки заявки
                }])

            self.assertEqual(BankPartnerRequestObject.query.count(), 1)
            bank_request = BankPartnerRequestObject.query.first()
            bank_request = copy(bank_request.__dict__)
            del bank_request['id']
            del bank_request['sent_date']
            del bank_request['_sa_instance_state']
            self.maxDiff = None
            self.assertEqual(
                bank_request, {
                    'bank_partner_id': bank_id,
                    'bank_contact_phone': '+79001231213',
                    'bank_contact_phone_general_manager': 'true',
                    'batch_id': batch_id,
                    'bank_partner_caption': u'«Альфа-банк»',
                    'send_private_data': True,
                    'status': 'failed'
                })
    def test_async_render_empty_protocol(self):
        DocRequisitiesStorage.get_batch_descriptor(
            DocumentBatchTypeEnum.DBT_NEW_LLC)['doc_types'] = [
                DocumentTypeEnum.DT_PROTOCOL
            ]

        with self.app.app_context():
            batch = DocumentBatchDbObject(
                batch_type=DocumentBatchTypeEnum.DBT_NEW_LLC,
                status=BatchStatusEnum.BS_NEW,
                _documents=[],
                data={},
                _owner=self.user._id)
            batch_id = batch.insert(self.db)

            founder_otvetstvennyi = PrivatePersonDbObject(
                **{
                    "_owner":
                    self.user._id,
                    "name":
                    u"",
                    "surname":
                    u"",
                    "patronymic":
                    u"",
                    "inn":
                    "781108730780",
                    "sex":
                    "male",
                    "birthdate":
                    datetime.now() - timedelta(days=365 * 30),
                    "birthplace":
                    u"Россия, деревня Гадюкино",
                    "passport": {
                        "document_type": PersonDocumentTypeEnum.PD_INTERNAL,
                        "series": u"1123",
                        "number": u"192837",
                        "issue_date": datetime.now() -
                        timedelta(days=365 * 14),
                        "issue_depart":
                        u"УМВД Гадюкинского района Гадюкинской области",
                        "depart_code": u"111987"
                    },
                    "ogrnip":
                    "123456789012345",
                    "address": {
                        "region": RFRegionsEnum.RFR_SPB,
                        "index": 198209,
                        "district_type": DistrictTypeEnum.DIT_DISTRICT,
                        "district": u"Пушкинский",
                        "city_type": CityTypeEnum.CIT_CITY,
                        "city": u"Гадюкино",
                        "village_type": VillageTypeEnum.VIT_HUTOR,
                        "village": u"близ Диканьки",
                        "street_type": StreetTypeEnum.STT_BOULEVARD,
                        "street": u"Мотоциклистов",
                        "house_type": HouseTypeEnum.HOT_HOUSE,
                        "house": "4",
                        "building_type": BuildingTypeEnum.BIT_HOUSING,
                        "building": "2",
                        "flat_type": FlatTypeEnum.FLT_OFFICE,
                        "flat": "705",
                    },
                    "caption":
                    u"Сантехник",
                    "phone":
                    "+79210001122",
                    "email":
                    "*****@*****.**",
                    "living_country_code":
                    3,
                    "living_address":
                    u"г. Санкт-Петербург, д. Гадюкино, бульвар Мотоциклистов казарма 4, кв. 705"
                })
            founder_otvetstvennyi.insert(self.db)

            company_founder = CompanyDbObject(
                **{
                    "_owner": self.user._id,
                    "ogrn": "1234567890123",
                    "inn": "781108730780",
                    "kpp": "999999999",
                    "general_manager_caption": u"генеральный директор",
                    "full_name": u"Том и Джери",
                    "short_name": u"ТиД",
                    "general_manager": {},
                    "address": {
                        "region": RFRegionsEnum.RFR_SPB,
                        "index": 123131,
                        "street_type": StreetTypeEnum.STT_STREET,
                        "street": u"Седова",
                        "house_type": HouseTypeEnum.HOT_HOUSE,
                        "house": "2",
                        "flat_type": FlatTypeEnum.FLT_OFFICE,
                        "flat": "2",
                    },
                    "phone": "+7(812)1234567"
                })
            company_founder.insert(self.app.db)

            new_batch_db_object = DocumentBatchDbObject(
                data={
                    u"address_type":
                    u"office_address",
                    u"founders": [{
                        u"founder": {
                            u"_id": company_founder.id,
                            u"type": u"company"
                        },
                        u"nominal_capital": 12312.22,
                        u"share": 85
                    }, {
                        u"founder": {
                            u"_id": founder_otvetstvennyi.id,
                            u"type": u"person"
                        },
                        u"nominal_capital": 1500.5,
                        u"share": 15
                    }],
                },
                batch_type=DocumentBatchTypeEnum.DBT_NEW_LLC)

            batch = DocumentBatch.parse_raw_value(
                new_batch_db_object.as_dict(), False)
            structure = batch.get_api_structure()
            del structure['batch_type']
            batch_json = json.dumps(structure)
            result = self.test_client.post('/batch/update/',
                                           data={
                                               'batch_id': unicode(batch_id),
                                               'batch': batch_json
                                           })
            self.assertEqual(result.status_code, 200)

            db_batch = DocumentBatchDbObject.query.filter_by(
                id=batch_id).first()
            new_user_doc_id = db_batch._documents[0].id

            result = self.test_client.get(
                '/batch/document/state/?batch_id=%s&document_id=%s' %
                (batch_id, new_user_doc_id))
            self.assertEqual(result.status_code, 200)
            result_data = json.loads(result.data)
            del result_data['result']['document_id']
            self.assertEqual(
                result_data, {
                    u'result': {
                        u'state': u'new',
                        u'links': {
                            u'pdf': None,
                            u'jpeg': []
                        }
                    }
                })

            result = self.test_client.post('/batch/document/render/',
                                           data={
                                               'batch_id':
                                               unicode(batch_id),
                                               'document_id':
                                               unicode(new_user_doc_id)
                                           })
            self.assertEqual(result.status_code, 200)
            result_data = json.loads(result.data)
            self.assertEqual(result_data, {u'result': True})

            result = self.test_client.get(
                '/batch/document_preview/state/?batch_id=%s&document_id=%s' %
                (unicode(batch_id), unicode(new_user_doc_id)))
            self.assertEqual(result.status_code, 200)
            result_data = json.loads(result.data)
            self.assertEqual(result_data['result']['state'], 'rendered')
            self.assertTrue(result_data['result']['links']['pdf'].startswith(
                u'http://service.zz/storage/'))
    def test_async_render_empty_r11001(self):
        DocRequisitiesStorage.get_batch_descriptor(
            DocumentBatchTypeEnum.DBT_NEW_LLC)['doc_types'] = [
                DocumentTypeEnum.DT_P11001
            ]

        with self.app.app_context():
            batch = DocumentBatchDbObject(
                batch_type=DocumentBatchTypeEnum.DBT_NEW_LLC,
                status=BatchStatusEnum.BS_NEW,
                _documents=[],
                data={},
                _owner=self.user._id)
            batch_id = batch.insert(self.db)

            new_batch_db_object = DocumentBatchDbObject(
                data={}, batch_type=DocumentBatchTypeEnum.DBT_NEW_LLC)

            batch = DocumentBatch.parse_raw_value(
                new_batch_db_object.as_dict(), False)
            structure = batch.get_api_structure()
            del structure['batch_type']
            batch_json = json.dumps(structure)
            result = self.test_client.post('/batch/update/',
                                           data={
                                               'batch_id': unicode(batch_id),
                                               'batch': batch_json
                                           })
            self.assertEqual(result.status_code, 200)

            db_batch = DocumentBatchDbObject.query.filter_by(
                id=batch_id).first()
            new_user_doc_id = db_batch._documents[0].id
            result = self.test_client.get(
                '/batch/document/state/?batch_id=%s&document_id=%s' %
                (batch_id, new_user_doc_id))
            self.assertEqual(result.status_code, 200)
            result_data = json.loads(result.data)
            del result_data['result']['document_id']
            self.assertEqual(
                result_data, {
                    u'result': {
                        u'state': u'new',
                        u'links': {
                            u'pdf': None,
                            u'jpeg': []
                        }
                    }
                })

            result = self.test_client.post('/batch/document/render/',
                                           data={
                                               'batch_id': unicode(batch_id),
                                               'document_id': new_user_doc_id
                                           })
            self.assertEqual(result.status_code, 200)
            result_data = json.loads(result.data)
            self.assertEqual(result_data, {u'result': True})

            result = self.test_client.get(
                '/batch/document/state/?batch_id=%s&document_id=%s' %
                (batch_id, new_user_doc_id))
            self.assertEqual(result.status_code, 200)
            result_data = json.loads(result.data)
            self.assertEqual(result_data['result']['state'], 'rendered')
            self.assertTrue(result_data['result']['links']['pdf'].startswith(
                u'http://service.zz/storage/'))
Esempio n. 22
0
    def test_request_bank(self):
        with self.app.app_context():
            DocRequisitiesStorage.get_batch_descriptor(
                DocumentBatchTypeEnum.DBT_NEW_LLC)['doc_types'] = [
                    DocumentTypeEnum.DT_P11001
                ]

            general_manager_person = self.create_person(self.user)
            batch = self.create_batch(DocumentBatchTypeEnum.DBT_NEW_LLC,
                                      self.user)
            batch.data = {
                u"full_name": u"фывафыва",
                u"short_name": u"Бокс",
                u"address": {
                    "street_type": u"ул",
                    "index": 191186,
                    "house": u"4",
                    "region": u"Санкт-Петербург",
                    "flat": u"12",
                    "street": u"Большая Морская",
                    "address_string":
                    u"г Санкт-Петербург, ул Большая Морская, д 4, кв 12",
                    "flat_type": u"кв",
                    "house_type": u"д",
                    "long_form_mode": True,
                    "ifns": u"7841",
                    "okato": u"92401385000",
                },
                u"address_type": u"general_manager_registration_address",
                u"general_manager_caption": u"повелитель",
                u"general_manager": {
                    "_id": general_manager_person.id,
                    "type": u"person"
                }
            }
            batch.result_fields = {
                'ifns_reg_info': {
                    'status': 'registered',
                    'reg_date': datetime.now(),
                    'full_name': u"Лютик",
                    'ogrn': 1095543023135
                }
            }
            sqldb.session.commit()
            batch_id = batch.id

            new_partner = BankPartnersObject(
                id=str(ObjectId()),
                region=[RFRegionsEnum.RFR_SPB],
                city=[RFRegionsEnum.RFR_SPB],
                enabled=True,
                sort_index=10,
                link=u'http://ya.ru',
                banner=u'http://yastatic.net/morda-logo/i/logo.svg',
                title=u'Йандекс',
                conditions=[])
            sqldb.session.add(new_partner)
            sqldb.session.commit()
            bank_id = new_partner.id

            svc = BankPartnersServiceObject(
                id=str(ObjectId()),
                type='email',
                email='test_email@test_domain.zz',
                fields=partners_manage_commands._BANK_PARTNER_SCHEMA,
                template_name='account_creation_consultation_request',
                bank_partner_id=bank_id)
            sqldb.session.add(svc)
            sqldb.session.commit()

            result = self.test_client.post(
                '/partners/banks/send/',
                data={
                    'batch_id': batch_id,
                    'bank_id': bank_id,
                    'bank_contact_phone_general_manager': True,
                    'bank_contact_phone': "+79001231213",
                    'send_private_data': True
                })
            self.assertEqual(result.status_code, 200)
            data = json.loads(result.data)
            batch = data['result']

            # DocumentBatchDbObject.get_collection(self.db).update({'_id': batch_id}, {
            #     '$set': {
            #         'data.ogrn': 1095543023135
            #     }
            # })
            # result = self.test_client.post('/partners/banks/send/', data={
            #     'batch_id': batch_id,
            #     'bank_id': bank_id,
            #     'bank_contact_phone_general_manager': True,
            #     'bank_contact_phone': "+79001231213",
            #     'send_private_data': True
            # })
            # self.assertEqual(result.status_code, 200)
            data = json.loads(result.data)
            batch = data['result']

            self.assertNotIn('error_info', batch)
            self.assertIn('result_fields', batch)

            result_fields = batch['result_fields']
            self.assertIn('bank_partner_requests', result_fields)
            self.maxDiff = None
            del result_fields['bank_partner_requests'][0]['sent_date']
            self.assertEqual(
                result_fields['bank_partner_requests'],
                [{
                    'bank_partner_id': str(bank_id),
                    'bank_contact_phone': '+79001231213',
                    'bank_contact_phone_general_manager': True,
                    # идентификатор партнера по банковскому обслуживанию
                    'bank_partner_caption': u'Йандекс',
                    # название банка-партнера
                    'send_private_data': True
                    # дата отправки заявки
                }])

            self.assertEqual(BankPartnerRequestObject.query.count(), 1)
            bank_request = BankPartnerRequestObject.query.first()
            bank_request = copy(bank_request.__dict__)
            del bank_request['id']
            del bank_request['sent_date']
            del bank_request['_sa_instance_state']
            self.maxDiff = None
            self.assertEqual(
                bank_request, {
                    'bank_partner_id': bank_id,
                    'bank_contact_phone': '+79001231213',
                    'bank_contact_phone_general_manager': 'true',
                    'batch_id': batch_id,
                    'bank_partner_caption': u'Йандекс',
                    'send_private_data': True,
                    'status': 'success'
                })
Esempio n. 23
0
def act(action, batch_db, previous_event_data, plugin_config, logger, config):
    assert batch_db
    if action != 'schedule':
        logger.error(u"Invalid action %s for task_scheduler plugin" % action)
        return False

    descriptor_name, task_to_schedule = plugin_config['action'].split('.')
    descriptor = DocRequisitiesStorage.get_batch_descriptor(descriptor_name)
    assert descriptor
    batch_actions = descriptor.get('actions') or {}
    if task_to_schedule not in batch_actions:
        logger.error(u"Invalid task name %s for task_scheduler plugin" %
                     task_to_schedule)
        return False

    source_data = copy(plugin_config)
    source_data['<batch>'] = batch_db
    source_data['<app_config>'] = config
    source_data['<current_user>'] = batch_db._owner
    source_data['<previous_event_data>'] = previous_event_data

    task_id = plugin_config.get('task_id', None)

    if task_id and isinstance(task_id, dict):
        task_id = transform_field_with_schema(source_data, task_id).db_value()

    dt_type = plugin_config['dt_type']

    event_data = {
        'task_to_schedule': task_to_schedule,
        'dt_type': dt_type,
        '<action_dt>': datetime.utcnow(),
    }

    if dt_type == 'exact_time_every_day':
        dt_format = plugin_config['dt_format']
        dt_exact_time = plugin_config['dt_exact_time']
        dt_time_zone_region = plugin_config.get('dt_time_zone_region',
                                                u'Москва')
        dt_not_earlier = plugin_config.get('dt_not_earlier', None)

        if dt_format and isinstance(dt_format, dict):
            dt_format = transform_field_with_schema(source_data,
                                                    dt_format).db_value()
        if dt_exact_time and isinstance(dt_exact_time, dict):
            dt_exact_time = transform_field_with_schema(
                source_data, dt_exact_time).db_value()
        if dt_time_zone_region and isinstance(dt_time_zone_region, dict):
            dt_time_zone_region = transform_field_with_schema(
                source_data, dt_time_zone_region)
            if dt_time_zone_region:
                dt_time_zone_region = dt_time_zone_region.db_value()
        if dt_not_earlier and isinstance(dt_not_earlier, dict):
            dt_not_earlier = transform_field_with_schema(
                source_data, dt_not_earlier).db_value()

        tz_name = RFRegionsEnum.get_time_zone(
            dt_time_zone_region) or "Europe/Moscow"
        now = datetime.utcnow()
        dt = calc_fixed_time_not_earlier(now, dt_exact_time,
                                         dt_not_earlier - now, tz_name)

        event_data.update({
            'dt': dt,
            'dt_format': dt_format,
            'dt_time_zone_region': dt_time_zone_region,
            'dt_not_earlier': dt_not_earlier,
            'tz_name': tz_name
        })
    else:
        raise NotImplementedError()

    try:
        new_task = CeleryScheduler.post(
            'fw.async_tasks.scheduler.run_scheduled_task',
            eta=dt,
            args=(descriptor_name, task_to_schedule, batch_db.id),
            task_id=task_id,
            force_replace_task=True)
        event_data['task_id'] = new_task.id
    except Exception:
        logger.exception(u"Failed to schedule task")
        return False
    return True
Esempio n. 24
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
Esempio n. 25
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