示例#1
0
def render_batch_documents(batch_id=None, document_type=None):
    batch = DocumentBatchDbObject.query.filter_by(id=batch_id,
                                                  _owner=current_user,
                                                  deleted=False).first()
    if not batch:
        raise errors.BatchNotFound()
    batch_manager = BatchManager.init(batch)

    document_types = json.loads(document_type)
    if not isinstance(document_types, list) and not isinstance(
            document_types, tuple):
        raise errors.InvalidParameterValue('document_type')

    doc_type_set = set()
    for doc_type in document_types:
        if not batch_manager.check_doc_type_support(batch.batch_type,
                                                    doc_type):
            raise errors.InvalidParameterValue('document_type')
        doc_type_set.add(doc_type)

    action_descriptor = {'plugin': 'doc_builder', 'action': 'render_group'}

    event_data = {'doc_types': list(doc_type_set), 'batch_id': batch.id}

    BatchManager.perform_action(action_descriptor, batch, event_data,
                                current_app.logger, current_app.config)
    return {"result": True}
示例#2
0
def get_render_batch_documents_state(batch_id=None, document_types=None):
    batch = DocumentBatchDbObject.query.filter_by(id=batch_id,
                                                  _owner=current_user,
                                                  deleted=False).first()
    if not batch:
        raise errors.BatchNotFound()

    batch_manager = BatchManager.init(batch)
    try:
        document_types = json.loads(document_types)
        if not isinstance(document_types, list) and not isinstance(
                document_types, tuple):
            raise Exception()
    except Exception:
        raise errors.InvalidParameterValue('document_type')

    doc_type_set = set()
    for doc_type in document_types:
        if not batch_manager.check_doc_type_support(batch.batch_type,
                                                    doc_type):
            raise errors.InvalidParameterValue('document_type')
        doc_type_set.add(doc_type)

    result = []

    for doc_type in doc_type_set:
        doc_obj = BatchDocumentDbObject.query.filter_by(
            batch_id=batch_id, document_type=doc_type).first()
        if not doc_obj:
            result.append({
                'state': UserDocumentStatus.DS_NEW,
                'document_type': doc_type
            })
            continue

        doc_info = {'state': doc_obj.status, 'document_type': doc_type}

        if doc_obj.status == UserDocumentStatus.DS_RENDERED:
            if doc_obj.file:
                doc_info['links'] = {
                    'pdf': FileStorage.get_url(doc_obj.file,
                                               current_app.config),
                    'jpeg': []
                }
                result.append(doc_info)
            else:
                current_app.logger.debug(
                    u"Not found rendered documents for rendered document %s. "
                    u"Returning as rendering_failed" % doc_type)
                result.append({
                    'state': UserDocumentStatus.DS_RENDERING_FAILED,
                    'document_type': doc_type
                })
        else:
            result.append(doc_info)

    return result
示例#3
0
def get_company_person_data_for_ifns(founder_applicant, reg_responsible_object, email):
    person_data = None
    company_data = None

    reg_responsible_person = None
    try:
        if reg_responsible_object and '_id' in reg_responsible_object and 'type' in reg_responsible_object:
            obj_id = reg_responsible_object['_id']
            obj_type = reg_responsible_object['type']
            if obj_type == 'person':
                reg_responsible_person = obj_id
            else:
                reg_responsible_company = CompanyDbObject.query.filter_by(id=obj_id).scalar()
                if reg_responsible_company and reg_responsible_company.general_manager:
                    reg_responsible_person = reg_responsible_company.general_manager['_id']
    except Exception:
        pass

    if reg_responsible_person:
        person_obj = PrivatePersonDbObject.query.filter_by(id=reg_responsible_person).scalar()
        if not person_obj:
            raise errors.InvalidParameterValue("reg_responsible_person")
        person_data = {
            "name": person_obj.name or u"",
            "surname": person_obj.surname or u"",
            "patronymic": person_obj.patronymic or u"",
            "phone": person_obj.phone,
            "email": email,
            "inn": person_obj.inn
        }
        return None, person_data

    if FounderTypeEnum.TYPE_CLS(founder_applicant['founder_type']) == FounderTypeEnum.FT_PERSON:
        person_obj = PrivatePersonDbObject.query.filter_by(id=founder_applicant['person']['_id']).scalar()
        if not person_obj:
            raise errors.InvalidParameterValue("founder_applicant")
        person_data = {
            "name": person_obj.name or u"",
            "surname": person_obj.surname or u"",
            "patronymic": person_obj.patronymic or u"",
            "phone": person_obj.phone,
            "email": email,
            "inn": person_obj.inn
        }
    else:
        company_obj = CompanyDbObject.query.filter_by(id=founder_applicant['company']['_id']).scalar()
        general_manager = company_obj.general_manager
        if not general_manager or not company_obj:
            raise errors.InvalidParameterValue("founder_applicant")
        company_data = {
            "name": company_obj.full_name,
            "phone": general_manager.phone,
            "email": email,
            "inn": company_obj.inn
        }
    return company_data, person_data
def create_company(company=None):
    try:
        company_doc = CompanyObject.parse_raw_value(company, api_data=True)
        if not company_doc:
            raise Exception()
    except Exception:
        current_app.logger.exception(u"Failed to validate company data")
        raise errors.InvalidParameterValue('company')

    try:
        company_doc.validate(strict=False)
    except Exception, ex:
        raise errors.InvalidParameterValue('company')
示例#5
0
def notarius_schedule(notarius_id=None, **kwargs):
    empty_result = {'result': {"nearest_time": None, "slots": []}}

    dt = kwargs.get('datetime', None)
    if not dt:
        raise errors.InvalidParameterValue('datetime')

    notarius_db = NotariusObject.query.filter_by(id=notarius_id).scalar()
    if not notarius_db:
        raise errors.NotariusNotFound()

    now = datetime.utcnow()
    two_weeks = timedelta(14)

    dt = datetime(dt.year, dt.month, dt.day)
    if dt < now or dt > now + two_weeks:
        return empty_result

    day_from, day_to = dt, dt + timedelta(days=1)

    days = NotariusObject.get_notarius_schedule(notarius_db,
                                                day_from=day_from,
                                                day_to=day_to)
    days = filter(lambda y: y['slots'],
                  sorted(days, key=lambda x: x['nearest_time']))
    days = filter(
        lambda x: datetime.strptime(x['nearest_time'], DocDateTimeField.FORMAT)
        .date() == dt.date(), days)
    if not days:
        return empty_result

    return {'result': days[0]}
示例#6
0
def _validate(arg_name, validator, required_args):
    if isinstance(validator, ArgumentValidator):
        validator.application = current_app
        try:
            if not len(request.form) and not len(
                    request.args) and request.data:
                from werkzeug.urls import url_decode

                args = url_decode(request.data)
                if arg_name not in args:
                    raise KeyError(arg_name)
                value = args[arg_name]
            else:
                value = request.form[
                    arg_name] if arg_name in request.form else request.args[
                        arg_name]
            if not validator.validate(value):
                raise errors.InvalidParameterValue(arg_name)
        except KeyError:
            if validator.required:
                raise errors.MissingRequiredParameter(arg_name)
            value = validator.default_value
        required_args[arg_name] = validator.get_value(
            value) if value is not None else None
    else:
        raise ValueError(
            "Invalid parameter in argument validator description: %s" %
            str(validator))
示例#7
0
def notarius_list_by_region(region=None):
    if not RFRegionsEnum.validate(region):
        raise errors.InvalidParameterValue('region')

    query = NotariusObject.query.filter_by(region=region)
    result = [item.get_api_structure() for item in query]
    return {'result': result}
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')
示例#9
0
def get_car_insurances(search=None, limit=100, offset=0, **kwargs):
    if 'type' not in kwargs:
        raise errors.MissingRequiredParameter('type')
    type_arg = kwargs['type']
    if type_arg != 'osago':
        raise errors.InvalidParameterValue('type')

    if search:
        query = CarAssurance.query.filter_by(full_name=search).order_by(
            CarAssurance.full_name)
    else:
        query = CarAssurance.query.filter().order_by(CarAssurance.short_name)

    total = query.count()
    query = query.limit(limit).offset(offset)
    count = query.count()

    result = {
        'total':
        total,
        'count':
        count,
        'insurances': [{
            "id": i.id,
            "short_name": i.short_name,
            "full_name": i.full_name
        } for i in query]
    }
    return {'result': result}
示例#10
0
def get_external_login_url(social_network=None):
    if social_network not in ('facebook', 'vk', 'google'):
        raise errors.InvalidParameterValue('social_network')

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

    config = current_app.config
    next_page = request.args['next_page']

    if '?' in next_page:
        next_page = next_page.split('?')[0]
    current_app.logger.debug(u"2 redirect url: %s" % next_page)

    token_url = backend.get_token_url(config, next_page=next_page)
    return {"result": token_url}
示例#11
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()}
示例#12
0
def ifns_get_reservations(batch_id=None):
    batch_db = DocumentBatchDbObject.query.filter_by(id=batch_id, _owner=current_user, deleted=False).scalar()
    if not batch_db:
        raise BatchNotFound()
    if batch_db.status != BatchStatusEnum.BS_FINALISED:
        raise errors.InvalidParameterValue('batch_id')

    booking = IfnsBookingObject.query.filter(
        IfnsBookingObject.batch_id == batch_id,
        IfnsBookingObject._discarded == False,
        IfnsBookingObject.reg_info.__ne__(None)
    ).first()

    try:
        name = batch_db.data['full_name']
        full_name = u"Общество с ограниченной ответственностью \"%s\"" % name
    except Exception:
        current_app.logger.exception(u"Failed to collect data")
        raise errors.InvalidParameterValue('batch_id')

    if not booking:
        return {
            'result': {
                'full_name': full_name,
                'status': "unknown"
            }
        }

    result = {'result': {
        'full_name': full_name,
        'status': booking.reg_info.get('status', 'unknown')
    }}
    reg_date = booking.reg_info.get('reg_date', None)
    ogrn = booking.reg_info.get('ogrn', None)
    if reg_date:
        result['result']['reg_date'] = reg_date
    if ogrn:
        result['result']['ogrn'] = booking.reg_info.get('ogrn', None)
    return result
示例#13
0
def get_bank_partner_request_status(bank_id=None, batch_id=None):
    try:
        bank_id = ObjectId(bank_id)
    except Exception:
        raise errors.InvalidParameterValue('bank_id')
    try:
        ObjectId(batch_id)
    except Exception:
        raise errors.InvalidParameterValue('batch_id')

    current_bank_request = BankPartnerRequestObject.query.filter_by(
        bank_partner_id=bank_id, batch_id=batch_id).first()
    if not current_bank_request:
        raise errors.BatchNotFound()

    if current_bank_request and current_bank_request.status == 'sending' and \
       abs((datetime.utcnow() - current_bank_request.sent_date).total_seconds()) > 60:

        sqldb.session.delete(current_bank_request)
        sqldb.session.commit()
        raise errors.BatchNotFound()

    return {"result": current_bank_request['status']}
示例#14
0
def password_change(user_id=None, email=None, code=None, old_password=None, new_password=None):
    email = email.lower() if email else u""

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

    user = UserManager.change_password(user_id, code, old_password, new_password)
    if user and not current_user.is_authenticated:
        login_user(user)
    return {"result": True}
示例#15
0
def confirm_account(code=None, user_id=None):
    if len(code) != current_app.config['max_activation_link_length'] and \
                    len(code) != current_app.config['digital_activation_link_length']:
        raise errors.InvalidParameterValue('code')

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

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

    data = get_user_api_structure(user)
    return {"result": data}
示例#16
0
def notarius_list(batch_id=None):
    batch = DocumentBatchDbObject.query.filter_by(id=batch_id,
                                                  _owner=current_user,
                                                  deleted=False).scalar()
    if not batch:
        raise errors.InvalidParameterValue('batch_id')

    batch_manager = BatchManager.init(batch)
    assert batch_manager

    region = batch_manager.get_batch_region(batch_id)

    if not region:
        return {'result': []}
    query = NotariusObject.query.filter_by(region=region)
    result = [item.get_api_structure() for item in query]
    return {'result': result}
示例#17
0
def ifns_get_name(ifns=None):
    null_res = {'result': {
        'title': "",
        'has_booking': False,
        'address': None
    }}
    IFNS_LOGGER.debug("ifns_get_name")

    try:
        ifns = int(ifns)
        if ifns < 1 or ifns > 99999:
            raise ValueError()
    except Exception:
        raise errors.InvalidParameterValue('ifns')

    result = IfnsCatalogObject.query.filter_by(code=ifns).first()
    if not result:
        return null_res

    ifns_item = result
    if not ifns_item.rou:
        return null_res

    rou = ifns_item.rou
    if not rou or 'name' not in rou:
        return null_res

    title = rou['name']
    if not title:
        return null_res

    has_booking = (7700 <= ifns <= 7799) or (7800 <= ifns <= 7899)  # or (4700 <= ifns <= 4799)

    address = (ifns_item.rou or {}).get('address', {})
    if not isinstance(address, dict):
        address = {}

    return {'result': {
        "title": title,
        "has_booking": has_booking,
        "address": address
    }}
示例#18
0
def get_dep_okvads(department_id=None, batch_type=None):
    from services.ip_reg.okvad_utils import is_restricted_for_ip_okvad
    for c in OkvedCatalogObject.query.filter():
        if not c.departments:
            continue
        for dep in c.departments:
            if dep['id'] == department_id:
                okvad_list = dep['okvads']
                if not okvad_list:
                    continue
                result = [_okvad_to_json(item) for item in OkvadObject.query.filter(OkvadObject.okved.in_(okvad_list))]
                for i in xrange(len(result)):
                    result[i]['description'] = ""
                    code = result[i]['okved']
                    result[i]['code'] = code
                    del result[i]['okved']
                if batch_type == DocumentBatchTypeEnum.DBT_NEW_IP:
                    result = filter(lambda x: not is_restricted_for_ip_okvad(x['code']), result)
                return {'result': result}

    raise errors.InvalidParameterValue('department_id')
示例#19
0
def track_mail_status(batch_id=None, tracking=None):
    tracking = tracking.strip()
    if not tracking:
        raise errors.InvalidParameterValue('tracking')

    tracking_item = RussianPostTrackingItem.query.filter(
        RussianPostTrackingItem.batch_id == batch_id,
        RussianPostTrackingItem.tracking == tracking,
        RussianPostTrackingItem.owner_id != 111111
    ).first()

    if tracking_item:
        return {
            'result': True
        }

    RussianPostTrackingItem.query.filter(
        RussianPostTrackingItem.batch_id == batch_id,
        RussianPostTrackingItem.owner == current_user
    ).delete()
    sqldb.session.commit()

    batch = DocumentBatchDbObject.query.filter_by(id=batch_id, deleted=False).scalar()
    if not batch:
        raise errors.BatchNotFound()

    new_tracking = RussianPostTrackingItem(
        batch=batch,
        owner=current_user,
        tracking=tracking
    )

    sqldb.session.add(new_tracking)
    sqldb.session.commit()

    from services.russian_post.async_tasks import get_tracking_info_async
    get_tracking_info_async.delay(batch_id=batch.id)

    return {'result': True}
示例#20
0
@domain_objects_bp.route('/entity/person/create/', methods=['POST'])
@api_view
@login_required
@validate_arguments(person=JsonValidator())
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')

    try:
        person_doc.validate(strict=False)
    except Exception, ex:
        raise errors.InvalidParameterValue('person')

    person = person_doc.get_db_object()
    person._owner = current_user

    sqldb.session.add(person)
    sqldb.session.commit()

    result = person_doc.get_api_structure()
    result['id'] = person.id + "_person"
    return {"result": result}


@domain_objects_bp.route('/entity/person/', methods=['GET'])
@api_view
@login_required
示例#21
0
def signup(email=None, access_token=None, password=None, social_network=None):
    if "X-Forwarded-For" in request.headers and request.headers.getlist("X-Forwarded-For"):
        ip = request.headers.getlist("X-Forwarded-For")[0]
    elif "X-Real-Ip" in request.headers and request.headers.getlist("X-Real-Ip"):
        ip = request.headers.getlist("X-Real-Ip")[0]
    else:
        ip = request.remote_addr

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

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

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

    if access_token:
        password = ''

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

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

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

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

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

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

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

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

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

    return result
示例#22
0
def ifns_reserve(ifns=None, service=None, batch_id=None, **kwargs):
    dt = kwargs['datetime']
    service = int(service)

    result = None

    batch_db = DocumentBatchDbObject.query.filter_by(id=batch_id, _owner=current_user, deleted=False).scalar()
    if not batch_db:
        raise errors.InvalidParameterValue('batch_id')

    from services.llc_reg.llc_reg_manager import LlcRegBatchManager
    founder_applicant = LlcRegBatchManager.get_founder_applicant(batch_db, logger=current_app.logger)
    if not founder_applicant:
        raise errors.InvalidParameterValue("batch_id")

    reg_responsible_object = LlcRegBatchManager.get_reg_responsible_object(batch_db, logger=current_app.logger)

    if not batch_db.data:
        raise errors.InvalidParameterValue('batch_id')

    batch_data_data = batch_db.data
    if 'full_name' not in batch_data_data or not batch_data_data['full_name']:
        raise errors.InvalidParameterValue('batch_id')
    company_full_name = batch_data_data['full_name']

    ifns_data = ifns_manager.get_ifns_data(ifns)
    if not ifns_data or not ifns_data.rou:
        raise errors.InvalidParameterValue("ifns")

    rou = ifns_data.rou
    if 'code' not in rou:
        raise errors.InvalidParameterValue("ifns")

    code = rou['code']

    if service == IfnsServiceEnum.IS_REG_COMPANY:
        if code not in LLC_REG_INTERNAL_SERVICE_ID_MAP:
            raise errors.InvalidParameterValue("ifns")

        IFNS_LOGGER.debug(
            u"Trying to reserve ifns. ifns:%d, service:%s, dt:%s" % (int(ifns), unicode(service), unicode(dt)))
        company_data, person_data = get_company_person_data_for_ifns(founder_applicant, reg_responsible_object,
                                                                     current_user.email)

        obj_type = "person" if person_data is not None else "company"
        internal_ifns_service, internal_ifns_number = LLC_REG_INTERNAL_SERVICE_ID_MAP[code][obj_type]
        try:
            result = current_app.external_tools.book_ifns(person_data, company_data, internal_ifns_number,
                                                          internal_ifns_service, dt, IFNS_LOGGER)
        except Exception:
            IFNS_LOGGER.exception(u"Failed to reserve ifns.")
            raise
    elif service == IfnsServiceEnum.IS_RECEIVE_REG_DOCS:
        try:
            if code not in RECEIVE_REG_DOCS_INTERNAL_SERVICE_ID_MAP:
                raise errors.InvalidParameterValue("ifns")
            general_manager = batch_data_data.get('general_manager')
            if not general_manager or '_id' not in general_manager:
                raise errors.InvalidParameterValue("batch_id")
            general_manager_id = general_manager['_id']
            general_manager_obj = PrivatePersonDbObject.query.filter_by(id=general_manager_id).scalar()
            if not general_manager_obj:
                raise errors.InvalidParameterValue("batch_id")
            internal_ifns_service, internal_ifns_number = RECEIVE_REG_DOCS_INTERNAL_SERVICE_ID_MAP[code]
            company_data = {
                'inn': '0000000000',
                "name": company_full_name,
                "phone": general_manager_obj.phone,
                "email": current_user.email,
            }
            result = current_app.external_tools.book_ifns(None, company_data, internal_ifns_number,
                                                          internal_ifns_service, dt, IFNS_LOGGER)
        except Exception:
            IFNS_LOGGER.exception(u"Failed to reserve ifns.")
            raise

    if result:
        from fw.async_tasks import send_email
        try:
            booking = IfnsBookingObject(
                batch_id=batch_id,
                code=result['code'],
                date=result['date'],
                service=result['service'],
                phone=result['phone'],
                window=result['window'],
                address=result['address'],
                service_id=service,
                ifns=result['ifns'],
                how_to_get=result['how_to_get']
            )
            sqldb.session.add(booking)
            sqldb.session.commit()

            IFNS_LOGGER.debug(u"Reserverd ifns. booking id: %s" % booking.id)

            social_link = SocialServiceBackends.get_user_social_network_profile_url(current_user.id)
            rec_list = current_app.config['YURIST_EMAIL_LIST']
            llc_full_name = batch_db.data.get('full_name', "")
            docs = BatchManager.get_shared_links_to_rendered_docs(batch_db, current_app.config,
                                                                  IFNS_LOGGER)
            for recipient in rec_list:
                send_email.send_email.delay(
                    recipient,
                    'ifns_reservation_notification',
                    email=current_user.email,
                    mobile=current_user.mobile,
                    social_link=social_link,
                    full_name=llc_full_name,
                    ifns=result['ifns'],
                    booking_time=result['date'],
                    docs=docs
                )
            booking_field = IfnsBooking.db_obj_to_field(booking)
            return {'result': booking_field.get_api_structure()}
        except Exception, ex:
            IFNS_LOGGER.exception(u"Failed to save booking!")
            raise errors.ServerError()
示例#23
0
def ifns_schedule(ifns=None, service=None, batch_id=None, **kwargs):
    dt = kwargs['datetime']
    service = int(service)

    batch_db = DocumentBatchDbObject.query.filter_by(id=batch_id, _owner=current_user, deleted=False).scalar()
    if not batch_db:
        raise errors.InvalidParameterValue('batch_id')

    # todo: check batch type (new llc)

    from services.llc_reg.llc_reg_manager import LlcRegBatchManager
    founder_applicant = LlcRegBatchManager.get_founder_applicant(batch_db, logger=current_app.logger)

    if not founder_applicant:
        raise errors.InvalidParameterValue("batch_id")

    IFNS_LOGGER.debug(
        u"Trying to get ifns schedule. ifns:%d, service:%s, dt:%s" % (int(ifns), unicode(service), unicode(dt)))

    all_time_slots = []

    ifns_data = ifns_manager.get_ifns_data(ifns)
    if not ifns_data or not ifns_data.rou:
        raise errors.InvalidParameterValue("ifns")

    rou = ifns_data.rou
    if 'code' not in rou:
        raise errors.InvalidParameterValue("ifns")

    code = rou['code']

    if service == IfnsServiceEnum.IS_REG_COMPANY:
        if code not in LLC_REG_INTERNAL_SERVICE_ID_MAP:
            raise errors.InvalidParameterValue("ifns")

        # noinspection PyTypeChecker
        company_data, person_data = get_company_person_data_for_ifns(founder_applicant, None, current_user.email)

        obj_type = "person" if person_data is not None else "company"
        internal_ifns_service, internal_ifns_number = LLC_REG_INTERNAL_SERVICE_ID_MAP[code][obj_type]

        try:
            all_time_slots = current_app.external_tools.get_nalog_ru_time_slots(person_data,
                                                                                company_data,
                                                                                internal_ifns_number,
                                                                                internal_ifns_service, IFNS_LOGGER)
            if not all_time_slots:
                raise Exception()
        except Exception:
            IFNS_LOGGER.exception(u"Failed to get_nalog_ru_time_slots")
            raise

    elif service == IfnsServiceEnum.IS_RECEIVE_REG_DOCS:
        if code not in RECEIVE_REG_DOCS_INTERNAL_SERVICE_ID_MAP:
            raise errors.InvalidParameterValue("ifns")
        internal_ifns_service, internal_ifns_number = RECEIVE_REG_DOCS_INTERNAL_SERVICE_ID_MAP[code]

        company_data = _make_fake_company_data()

        try:
            all_time_slots = current_app.external_tools.get_nalog_ru_time_slots(None,
                                                                                company_data,
                                                                                internal_ifns_number,
                                                                                internal_ifns_service, IFNS_LOGGER)
            if not all_time_slots:
                raise Exception()
        except Exception:
            IFNS_LOGGER.exception(u"Failed to get_nalog_ru_time_slots")
            raise

    if not all_time_slots:
        return {
            'result': {
                'nearest_time': None,
                'slots': []
            }
        }

    td_min = timedelta(seconds=99999999)
    nearest_time = datetime.strptime(all_time_slots[0]['date'], "%Y-%m-%d")
    slots = all_time_slots[0]['time_slots']

    actual_slots = []

    dt_str = dt.strftime("%Y-%m-%d")
    for slot in all_time_slots:
        cur_date = datetime.strptime(slot['date'], "%Y-%m-%d")
        if slot['date'] == dt_str:
            actual_slots = slot['time_slots']
        td_cur = cur_date - dt if (cur_date > dt) else (dt - cur_date)
        if td_cur < td_min:
            td_min = td_cur
            nearest_time = cur_date
            slots = slot['time_slots']

    # IFNS_LOGGER.debug(u"Ifns schedule - succeeded. Nearest time: %s, Slots: %s" % (nearest_time.strftime("%Y-%m-%d"), json.dumps(slots)))
    return {'result': {
        'nearest_time': dt_str,
        'slots': actual_slots
    }}
示例#24
0
def login_external(social_network=None, next_page=""):
    class MyResp(Response):
        def set_cookie(self, key, value='', max_age=None, expires=None,
                       path='/', domain=None, secure=None, httponly=False):
            self.__name = key
            self.__val = value
            super(MyResp, self).set_cookie(key, value, max_age, expires, path, domain, secure, httponly)

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

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

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

    config = current_app.config

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

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

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

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

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

    return {"result": None}
示例#25
0
    def get_content_on_post(self, arguments=None, *args, **kwargs):

        logger = self.application.logger  # todo: ifns logger!
        cache = self.application.cache

        ifns = arguments['ifns']
        service = arguments['service']
        dt = arguments['datetime']
        founder_applicant = arguments['founder_applicant']
        service_nalog_ru_url = self.application.config['SERVICE_NALOG_RU_URL']

        try:
            company_data, person_data = yield AsyncIfnsProvider.get_company_person_data_for_ifns(
                founder_applicant, self.user.email, self.application.db)
        except Exception:
            logger.exception(u"Failed to collect data")
            raise errors.InvalidParameterValue("founder_applicant")

        try:
            reg_ifns = yield AsyncIfnsProvider.get_registration_ifns(
                int_to_ifns(ifns),
                cache,
                service_nalog_ru_url=service_nalog_ru_url)
        except Exception:
            logger.exception(
                u"Failed to get registration ifns. Address ifns: %s" %
                unicode(ifns))
            raise

        reg_ifns_name = reg_ifns['rou']['naimk']
        reg_ifns_addr = reg_ifns['adres']
        try:
            address = yield AsyncDadataProvider.get_detailed_address(
                reg_ifns_addr, cache)
            if not address:
                raise Exception()
        except Exception:
            logger.exception(
                u"Failed to get detailed address. Reg ifns address: %s" %
                unicode(reg_ifns_addr))
            raise
        region_name = address['suggestions'][0]['data']['region']

        try:
            result = yield AsyncIfnsProvider.get_nalog_ru_time_slots(
                person_data, company_data, reg_ifns_name, service, region_name,
                cache, logger)
        except errors.IfnsServiceUnavailable, ex:
            logger.exception(
                u"Failed to get schedule from ifns. Trying to get cached value"
            )
            try:
                result = yield AsyncIfnsProvider.get_nalog_ru_time_slots_cached(
                    not company_data, reg_ifns_name, service, region_name,
                    cache, logger)
                if len(result) < 8:
                    last_found_day = datetime.strptime(result[-1]['date'],
                                                       "%Y-%m-%d")
                    result += AsyncIfnsProvider.get_nalog_ru_default_time_slots(
                        region_name,
                        reg_ifns_name,
                        not company_data,
                        first_day=last_found_day,
                        days_to_get=8 - len(result))
            except CacheMiss, ex:
                logger.exception(u"Nothing in cache: returning defaults")
                result = AsyncIfnsProvider.get_nalog_ru_default_time_slots(
                    region_name, reg_ifns_name, not company_data)
示例#26
0
def request_bank_partner(bank_id=None,
                         batch_id=None,
                         bank_contact_phone_general_manager=False,
                         bank_contact_phone="",
                         send_private_data=None):

    if not bank_contact_phone_general_manager and not bank_contact_phone:
        raise errors.MissingRequiredParameter('bank_contact_phone')

    batch = DocumentBatchDbObject.query.filter_by(
        id=batch_id,
        _owner=current_user,
        deleted=False,
        batch_type=DocumentBatchTypeEnum.DBT_NEW_LLC).scalar()
    if not batch or not batch.data:
        raise errors.BatchNotFound()
    current_batch = DocumentBatch.db_obj_to_field(batch)

    partner = BankPartnersObject.query.filter_by(id=bank_id).first()
    if not partner:
        raise errors.InvalidParameterValue('partner_id')

    svc_data = BankPartnersServiceObject.query.filter_by(
        bank_partner_id=partner.id).first()
    if not svc_data:
        raise errors.ServerError()

    current_bank_request = BankPartnerRequestObject.query.filter_by(
        bank_partner_id=partner.id, batch_id=batch_id).first()
    if current_bank_request and current_bank_request.status in ('sending',
                                                                'success'):
        struct = current_batch.get_api_structure()
        return {'result': struct}

    if current_bank_request and abs(
        (datetime.utcnow() -
         current_bank_request.sent_date).total_seconds()) > 60:
        BankPartnerRequestObject.query.filter_by(
            id=current_bank_request.id).delete()
        sqldb.session.commit()
        current_bank_request = None

    svc_type = svc_data.type

    fields = svc_data.fields
    extra_context = {
        'bank_contact_phone_general_manager':
        bank_contact_phone_general_manager,
        'bank_contact_phone': bank_contact_phone,
        'send_private_data': send_private_data,
        'bank_title': partner.title
    }
    field_list = BatchManager.make_fields_from_data(
        batch_id, fields, current_app.config, extra_context=extra_context)

    context = {}
    errors_list = []
    for name in field_list:
        field = field_list[name]
        try:
            if not field.initialized:
                if field.required:
                    raise MissingRequiredFieldException(name)
            else:
                field.validate()
        except (InvalidFieldValueException, MissingRequiredFieldException), ex:
            if hasattr(field, "suppress_validation_errors"):
                suppress_validation_errors = field.suppress_validation_errors
                if isinstance(suppress_validation_errors, dict):
                    suppress_validation_condition = Condition(
                        suppress_validation_errors)
                    context = copy.copy(batch.data)
                    context.update(extra_context)
                    suppress_validation_errors = suppress_validation_condition.check(
                        context)
                if suppress_validation_errors:
                    continue

            if getattr(ex, 'ext_data', None):
                err_list = error_tree_to_list(ex.ext_data)
                error_field_paths = [{
                    'field': name + '.' + i['field'],
                    'error_code': i['error_code']
                } for i in err_list]
                errors_list.extend(error_field_paths)
            else:
                errors_list.append({
                    'field': name,
                    'error_code': ex.ERROR_CODE
                })
            current_app.logger.exception(u"Field %s validation error" % name)
            continue
        if field_list[name].initialized:
            context[name] = field_list[name]
示例#27
0
    def get_content_on_post(self, arguments=None, *args, **kwargs):

        logger = self.application.logger  # todo: ifns logger!
        cache = self.application.cache

        ifns = arguments['ifns']
        service = arguments['service']
        dt = arguments['datetime']
        founder_applicant = arguments['founder_applicant']
        batch_id = arguments['batch_id']
        reg_responsible_person = arguments.get('reg_responsible_person', None)
        service_nalog_ru_url = self.application.config['SERVICE_NALOG_RU_URL']

        try:
            company_data, person_data = yield AsyncIfnsProvider.get_company_person_data_for_ifns(
                founder_applicant, self.user.email, self.application.db)
        except Exception:
            logger.exception(u"Failed to collect data")
            raise errors.InvalidParameterValue("founder_applicant")

        try:
            reg_ifns = yield AsyncIfnsProvider.get_registration_ifns(
                int_to_ifns(ifns),
                cache,
                service_nalog_ru_url=service_nalog_ru_url)
        except Exception:
            logger.exception(
                u"Failed to get registration ifns. Address ifns: %s" %
                unicode(ifns))
            raise

        reg_ifns_name = reg_ifns['rou']['naimk']
        reg_ifns_addr = reg_ifns['adres']
        try:
            address = yield AsyncDadataProvider.get_detailed_address(
                reg_ifns_addr, cache)
            if not address:
                raise Exception()
        except Exception:
            logger.exception(
                u"Failed to get detailed address. Reg ifns address: %s" %
                unicode(reg_ifns_addr))
            raise
        region_name = address['suggestions'][0]['data']['region']

        # todo: remove booking tasks with the same batch_id:service. (remove objects (in statuses new & progress) & cancel tasks)
        try:
            result = yield AsyncIfnsProvider.book_ifns(
                person_data, company_data, reg_ifns_name, service, region_name,
                dt, reg_responsible_person, cache, logger)
        except errors.IfnsServiceUnavailable, ex:
            logger.exception(u"Failed to book ifns")
            booking_obj = IfnsBookingObject(
                **{
                    "batch_id": batch_id,
                    "person_data": person_data,
                    "company_data": company_data,
                    "reg_ifns_name": reg_ifns_name,
                    "service": service,
                    "region_name": region_name,
                    "reg_date": dt.strftime("%Y-%m-%dT%H:%M:%S"),
                    "reg_responsible_person": reg_responsible_person,
                    "status": IfnsBookingTaskStatus.BTS_NEW,
                    "error_info": None,
                    "user_email": self.user.email
                })
            sqldb.session.add(booking_obj)
            sqldb.session.commit()
            ifns_booking_task_id = booking_obj.id
            ifns_booking_tasks.book_ifns(str(ifns_booking_task_id))
            raise gen.Return({'error': True, 'error_type': "booking_queued"})
示例#28
0
    def update_profile(cls, auth_user, new_email, new_mobile=None):

        temp_user = auth_user.temporal
        if new_email:
            new_email = new_email.lower()

        if new_email and auth_user.email != new_email:
            if AuthUser.query.filter_by(email=new_email).count():
                raise errors.DuplicateEmail()

            auth_user.email = new_email
            auth_user.email_confirmed = False

            if temp_user:
                new_password = UserManager.generate_password()
                password = unicode(encrypt_password(new_password))

                link_code = cls._generate_link_code(True)

                activation_link = UserActivationLink(
                    link_type=ConfirmationLinkTypeEnum.CLT_PASSWORD,
                    link_code=link_code,
                    auth_user=auth_user
                )
                db.session.add(activation_link)

                from fw.async_tasks import send_email

                schema = cls.__config['WEB_SCHEMA']
                domain = cls.__config['DOMAIN']
                selfcare_url = u"%s://%s/account/?" % (schema, domain)
                selfcare_url = utm_args(selfcare_url, 'new_account_user_notify', auth_user.id)
                selfcare_url = cls.make_auth_url(selfcare_url, auth_user).get_url(cls.__config)
                tmpl_data = {
                    'password': new_password,
                    "link_code": activation_link.link_code,
                    'email': new_email,
                    "domain": domain,
                    "schema": schema,
                    "user_id": auth_user.uuid,
                    "selfcare_url": selfcare_url # {{'?'|utm_args('', user_id)}}
                }
                send_email.send_email.delay(new_email, "new_account_user_notify", **tmpl_data)
                auth_user.password = password
                auth_user.temporal = False

            UserManager.confirm_new_email(auth_user, new_email, email_type="confirm_email")
            db.session.commit()

        elif new_email == u'':
            # empty string: delete current email
            raise errors.InvalidParameterValue('email')

        if new_mobile and auth_user.mobile != new_mobile:
            if AuthUser.query.filter_by(mobile=new_mobile).count():
                raise errors.DuplicateMobile()

            auth_user.mobile = new_mobile
            auth_user.mobile_confirmed = False
            UserManager.confirm_new_mobile(auth_user, new_mobile)
            db.session.commit()
        elif new_mobile == u"":
            auth_user.mobile = None
            auth_user.mobile_confirmed = False
            db.session.commit()

        return auth_user