예제 #1
0
def check_kvitanciya():
    for i in ALL_IFNS_NUMBERS:
        if i > 999:
            continue
        data = {
            "addrFl": "Адрес",
            "addrUl": "Адрес",
            "addrFl_ifns": int_to_ifns(i),
            "addrFl_okatom": 40270562000,
            "addrUl_ifns": int_to_ifns(i),
            "addrUl_okatom": 40270562000,
            "sum": "4000",
            "c": "",
            "gp": "11|18210807010011000110|13|ul|4000",
            "inn": 840300383062,
            "fam": u"Петров",
            "nam": u"Александр",
            "otch": u"Николаевич",
            "payKind": "on",
            "bank": "",
            "region": ""
        }

        result = requests.post("https://service.nalog.ru/gp-pay.do", data, timeout=20)
        if result.status_code != 200 or 'application/pdf' != result.headers['content-type']:
            print("-%d" % i)
        else:
            with open('/home/skraev/kvit_list_add.txt', 'a') as f:
                f.write(str(i) + "\n")
            print("+%d" % i)
예제 #2
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)
예제 #3
0
def db_ifns_to_api(item):
    result_item = {
        'id': item.id,
        'ifns_code': int_to_ifns(item.code),
        'caption': item.name or u'',
        'address': item.address or u'',
        'phones': [phone.replace('(', '').replace(')', '') for phone in (item.tel or [])],
        'additional_info': item.comment or u''
    }
    if 'address_string' in result_item['address']:
        try:
            address = json.loads(result_item['address'])
            result_item['address'] = address.get('address_string', u'')
        except Exception:
            pass
    plat = item.plat or {}
    if plat:
        result_item['payment_details'] = {
            'payment_recipient_caption': plat.get('recipient_name', u''),
            'inn': plat.get('recipient_inn', u''),
            'kpp': plat.get('recipient_kpp', u''),
            'bank_caption': plat.get('bank_name', u''),
            'bik': plat.get('bik', u''),
            'account': plat.get('recipient_account', u'')
        }
    if item.rou:
        rou = item.rou
        result_item['llc_registration_ifns'] = {
            'ifns_reg_code': str(rou['code']),
            'caption': rou.get('name', u""),
            'address': rou.get('address', {}).get('address_string', u''),
            'phones': [phone.replace('(', '').replace(')', '') for phone in rou.get('tel', [])]
        }

    if item.rof:
        rof = item.rof
        result_item['ip_registration_ifns'] = {
            'ifns_reg_code': str(rof['code']),
            'caption': rof.get('name', u""),
            'address': rof.get('address', {}).get('address_string', u''),
            'phones': [phone.replace('(', '').replace(')', '') for phone in (rof or {}).get('tel', [])]
        }
    return result_item
예제 #4
0
def get_ifns_by_code(tax_office, service_nalog_ru_url):
    cache_key = address_utils.prepare_key('ifns_no_' + unicode(tax_office))
    result_text = current_app.external_tools.cache.get(cache_key)
    if not result_text:
        url = u"%s/addrno.do?l=6&g=%s" % (service_nalog_ru_url, int_to_ifns(tax_office))
        headers = {
            u"Referer": u"%s/addrno.do" % service_nalog_ru_url,
            u"Accept": "application/json, text/javascript, */*; q=0.01"
        }
        r = requests.get(url, headers=headers, timeout=20)
        if r.status_code != 200:
            return u""
        result_text = r.text
        current_app.external_tools.cache.set(cache_key, result_text, 3600 * 24)

    try:
        result = json.loads(result_text)
        return IfnsDescription(result["res"])
    except Exception:
        pass
예제 #5
0
def get_ifns_by_code(tax_office, service_nalog_ru_url):
    cache_key = address_utils.prepare_key('ifns_no_' + unicode(tax_office))
    result_text = current_app.external_tools.cache.get(cache_key)
    if not result_text:
        url = u"%s/addrno.do?l=6&g=%s" % (service_nalog_ru_url,
                                          int_to_ifns(tax_office))
        headers = {
            u"Referer": u"%s/addrno.do" % service_nalog_ru_url,
            u"Accept": "application/json, text/javascript, */*; q=0.01"
        }
        r = requests.get(url, headers=headers, timeout=20)
        if r.status_code != 200:
            return u""
        result_text = r.text
        current_app.external_tools.cache.set(cache_key, result_text, 3600 * 24)

    try:
        result = json.loads(result_text)
        return IfnsDescription(result["res"])
    except Exception:
        pass
예제 #6
0
def list_ifns():
    found = []
    s = requests.Session()
    s.get('https://service.nalog.ru/addrno.do')
    for ifns in xrange(0, 1000):
        result = s.get('https://service.nalog.ru/addrno.do?l=6&g=%s' % int_to_ifns(ifns))
        if result.status_code != 200:
            print('-%d' % ifns)
            continue
        try:
            data = result.json()
            res = data['res']
            if 'plat' in res and 'found' in res['plat'] and not res['plat']['found'] and len(res) == 1 and len(
                    res['plat']) == 1:
                raise Exception()
        except Exception:
            print('-%d' % ifns)
            continue
        found.append(ifns)
        with open('/home/skraev/ifns_list.txt', 'a') as f:
            f.write(str(ifns) + "\n")
        print('+%d' % ifns)
예제 #7
0
    def run(self):
        """
            Should be started every minute.
        """

        result = IfnsCatalogObject.query.filter(
            IfnsCatalogObject.updated.__ne__(None)
        ).order_by(IfnsCatalogObject.updated.asc()).first()

        if not result:
            self.logger.error(u"Failed to find ifns to update")
            return

        ifns_item = result
        ifns = ifns_item.code

        self.logger.info(u"Updating ifns %s" % unicode(ifns))

        ifns_item.updated = datetime.utcnow()
        sqldb.session.commit()

        s = requests.Session()
        s.get('https://service.nalog.ru/addrno.do', timeout=5)
        result = s.get('https://service.nalog.ru/addrno.do?l=6&g=%s' % int_to_ifns(ifns), timeout=5)
        if result.status_code != 200:
            self.logger.error(u"Failed to get data for ifns %s" % ifns)
            return

        data = {}
        try:
            data = result.json()
            res = data['res']

            required_fields = ('naimk', 'adres')
            if any([field not in res for field in required_fields]):
                if not ifns_item.naimk:
                    sqldb.session.delete(ifns_item)
                    sqldb.session.commit()
                raise Exception(u"Empty data")
            name = res['naimk']
            address = res['adres']
            old_address = ifns_item.address

            old_address_str = old_address['address_string'] if (
                isinstance(old_address, dict) and 'address_string' in old_address) else old_address

            # if address != old_address_str or isinstance(old_address_str, basestring):
            #                address = str_address_to_struct(address)

            tel = get_phone_list(res['tel'], self.logger) if 'tel' in res else None
            comment = res.get('coment', '')

            plat_src = res.get('plat', None)
            plat = {}
            if plat_src:
                plat['recipient_name'] = plat_src['naimpol']
                plat['recipient_kpp'] = plat_src['kpppol']
                plat['recipient_inn'] = plat_src['innpol']

                if plat_src['found']:
                    plat['bik'] = plat_src['bik']
                    plat['bank_name'] = plat_src['naimbank']
                    plat['recipient_account'] = plat_src['schetpol']

            rou = {}
            rou_src = res.get('rou', None)

            if rou_src:
                rou['name'] = rou_src['naimk']
                rou['code'] = rou_src['code']
                if 'tel' in rou_src:
                    rou['tel'] = get_phone_list(rou_src['tel'], self.logger)
                rou_addr = rou_src['adres']
                rou['address_str'] = rou_addr
                old_rou_addr_str = (ifns_item.rou or {}).get('address_str', "")
                if rou_addr != old_rou_addr_str:
                    rou['address'] = str_address_to_struct(rou_addr)
                else:
                    rou['address'] = (ifns_item.rou or {}).get('address', {})

            rof = {}
            rof_src = res.get('rof', None)

            if rof_src:
                rof['name'] = rof_src['naimk']
                rof['code'] = rof_src['code']
                if 'tel' in rof_src:
                    rof['tel'] = get_phone_list(rof_src['tel'], self.logger)
                rof['address'] = rof_src['adres']

            new_fields = {
                'name': name,
                'address': address,
                'comment': comment
            }
            unset_fields = {}
            if tel:
                new_fields['tel'] = tel
            else:
                unset_fields['tel'] = ""

            if plat:
                new_fields['plat'] = plat
            else:
                unset_fields['plat'] = ""

            if rou:
                new_fields['rou'] = rou
            else:
                unset_fields['rou'] = ""

            if rof:
                new_fields['rof'] = rof
            else:
                unset_fields['rof'] = ""

            # TODO:
            # if not unset_fields:
            #     col.update({'code': ifns}, {'$set': new_fields})
            # else:
            #     col.update({'code': ifns}, {'$set': new_fields, '$unset': unset_fields})
            # self.logger.info(u"ifns %s updated" % str(ifns))
        except Exception:
            self.logger.exception(u"Invalid data returned for ifns %s: \r\n %s" %
                                  (ifns, json.dumps(data, default=lambda x: unicode(x),
                                                    indent=1, ensure_ascii=False)))
            return
예제 #8
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"
            })
예제 #9
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)
예제 #10
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"})