dadata

package module
v2.0.0-...-ba1c2de Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: May 3, 2019 License: MIT Imports: 7 Imported by: 4

README

Client for DaData.ru

GoDoc Go Report Card Coverage Status Build Status

DaData API v2

Implemented Clean and Suggest methods.

Installation

go get gopkg.in/webdeskltd/dadata.v2

Usage

package main

import (
	"fmt"

	"gopkg.in/webdeskltd/dadata.v2"
)

func main() {
	daData := dadata.NewDaData("PUT_YOUR_API_KEY", "PUT_YOUR_SECRET_KEY")

	banks, err := daData.SuggestBanks(dadata.SuggestRequestParams{Query: "Кредитный", Count: 3})
	if nil != err {
		fmt.Println(err)
	}

	for _, bank := range banks {
		fmt.Println(bank.Data.Name.Full)
		fmt.Println(bank.Data.Bic)
	}

	// Output:
	// "МОСКОВСКИЙ КРЕДИТНЫЙ БАНК" (ПУБЛИЧНОЕ АКЦИОНЕРНОЕ ОБЩЕСТВО)
	// 044525659
	// КОММЕРЧЕСКИЙ БАНК "РЕСПУБЛИКАНСКИЙ КРЕДИТНЫЙ АЛЬЯНС" (ОБЩЕСТВО С ОГРАНИЧЕННОЙ ОТВЕТСТВЕННОСТЬЮ)
	// 044525860
	// ЖИЛИЩНО-КРЕДИТНЫЙ КОММЕРЧЕСКИЙ БАНК "ЖИЛКРЕДИТ" ОБЩЕСТВО С ОГРАНИЧЕННОЙ ОТВЕТСТВЕННОСТЬЮ
	// 044525325
}

more examples in examples_test.go

Licence

MIT see LICENSE

Documentation

Overview

Package dadata implemented cleaning (https://dadata.ru/api/clean/) and suggesting (https://dadata.ru/api/suggest/)

Index

Examples

Constants

View Source
const (
	QcSuccess = 0 // Исходное значение распознано уверенно. Не требуется ручная проверка.
	QcFailure = 1 // Исходное значение распознано с допущениями или не распознано. Требуется ручная проверка.
)

Определите, нужна ли дополнительная проверка оператором, используя код качества (qc):

View Source
const (
	QcCompleteSuitable               = 0  // Пригоден для почтовой рассылки
	QcCompleteNoRegion               = 1  // Не пригоден, нет региона
	QcCompleteNoCity                 = 2  // Не пригоден, нет города
	QcCompleteNoStreet               = 3  // Не пригоден, нет улицы
	QcCompleteNotHome                = 4  // Не пригоден, нет дома
	QcCompleteNoApartment            = 5  // Пригоден для юридических лиц или частных владений (нет квартиры)
	QcCompleteNotSuitable            = 6  // Не пригоден
	QcCompleteCompleteForeignAddress = 7  // Иностранный адрес
	QcCompleteCompleteNoKLADR        = 10 // Пригоден, но низкая вероятность успешной доставки (дом не найден в КЛАДР)
)

Определите пригодность к рассылке, используя код полноты адреса (qc_complete):

View Source
const (
	QcHouseExactMatch        = 2  // Дом найден по точному совпадению (КЛАДР)	Высокая
	QcHouseNotExpansionMatch = 3  // Различие в расширении дома (КЛАДР)	Средняя
	QcHouseRangeMatch        = 4  // Дом найден по диапазону (КЛАДР)	Средняя
	QcHouseNotFound          = 10 // Дом не найден (КЛАДР)	Низкая
)

Определите вероятность успешной доставки письма по адресу, используя код проверки дома (qc_house):

View Source
const (
	QcGeoExactCoordinates = 0 // Точные координаты
	QcGeoNearestHouse     = 1 // Ближайший дом
	QcGeoStreet           = 2 // Улица
	QcGeoLocality         = 3 // Населенный пункт
	QcGeoCity             = 4 // Город
	QcGeoNotDetermined    = 5 // Координаты не определены
)

Определите точность координат адреса доставки с помощью кода qc_geo:

View Source
const (
	QcConflictFullMath   = 0 // Телефон соответствует адресу
	QcConflictCityMath   = 2 // Города адреса и телефона отличаются
	QcConflictRegionMath = 3 // Регионы адреса и телефона отличаются
)

Проверьте, указал ли клиент телефон, соответствующий его адресу, с помощью кода qc_conflict (удобно для проверки уровня риска):

Variables

This section is empty.

Functions

This section is empty.

Types

type Address

type Address struct {
	Source               string `json:"source"`                  // Исходный адрес одной строкой
	Result               string `json:"result"`                  // Стандартизованный адрес одной строкой
	PostalCode           string `json:"postal_code"`             // Индекс
	Country              string `json:"country"`                 // Страна
	RegionFiasID         string `json:"region_fias_id"`          // Код ФИАС региона
	RegionKladrID        string `json:"region_kladr_id"`         // Код КЛАДР региона
	RegionWithType       string `json:"region_with_type"`        // Регион с типом
	RegionType           string `json:"region_type"`             // Тип региона (сокращенный)
	RegionTypeFull       string `json:"region_type_full"`        // Тип региона
	Region               string `json:"region"`                  // Регион
	AreaFiasID           string `json:"area_fias_id"`            // Код ФИАС района в регионе
	AreaKladrID          string `json:"area_kladr_id"`           // Код КЛАДР района в регионе
	AreaWithType         string `json:"area_with_type"`          // Район в регионе с типом
	AreaType             string `json:"area_type"`               // Тип района в регионе (сокращенный)
	AreaTypeFull         string `json:"area_type_full"`          // Тип района в регионе
	Area                 string `json:"area"`                    // Район в регионе
	CityFiasID           string `json:"city_fias_id"`            // Код ФИАС города
	CityKladrID          string `json:"city_kladr_id"`           // Код КЛАДР города
	CityWithType         string `json:"city_with_type"`          // Город с типом
	CityType             string `json:"city_type"`               // Тип города (сокращенный)
	CityTypeFull         string `json:"city_type_full"`          // Тип города
	City                 string `json:"city"`                    // Город
	CityArea             string `json:"city_area"`               // Административный округ (только для Москвы)
	CityDistrictFiasID   string `json:"city_district_fias_id"`   // Код ФИАС района города (заполняется, только если район есть в ФИАС)
	CityDistrictKladrID  string `json:"city_district_kladr_id"`  // Код КЛАДР района города (не заполняется)
	CityDistrictWithType string `json:"city_district_with_type"` // Район города с типом
	CityDistrictType     string `json:"city_district_type"`      // Тип района города (сокращенный)
	CityDistrictTypeFull string `json:"city_district_type_full"` // Тип района города
	CityDistrict         string `json:"city_district"`           // Район города
	SettlementFiasID     string `json:"settlement_fias_id"`      // Код ФИАС нас. пункта
	SettlementKladrID    string `json:"settlement_kladr_id"`     // Код КЛАДР нас. пункта
	SettlementWithType   string `json:"settlement_with_type"`    // Населенный пункт с типом
	SettlementType       string `json:"settlement_type"`         // Тип населенного пункта (сокращенный)
	SettlementTypeFull   string `json:"settlement_type_full"`    // Тип населенного пункта
	Settlement           string `json:"settlement"`              // Населенный пункт
	StreetFiasID         string `json:"street_fias_id"`          // Код ФИАС улицы
	StreetKladrID        string `json:"street_kladr_id"`         // Код КЛАДР улицы
	StreetWithType       string `json:"street_with_type"`        // Улица с типом
	StreetType           string `json:"street_type"`             // Тип улицы (сокращенный)
	StreetTypeFull       string `json:"street_type_full"`        // Тип улицы
	Street               string `json:"street"`                  // Улица
	HouseFiasID          string `json:"house_fias_id"`           // Код ФИАС дома
	HouseKladrID         string `json:"house_kladr_id"`          // Код КЛАДР дома
	HouseType            string `json:"house_type"`              // Тип дома (сокращенный)
	HouseTypeFull        string `json:"house_type_full"`         // Тип дома
	House                string `json:"house"`                   // Дом
	BlockType            string `json:"block_type"`              // Тип корпуса/строения (сокращенный)
	BlockTypeFull        string `json:"block_type_full"`         // Тип корпуса/строения
	Block                string `json:"block"`                   // Корпус/строение
	FlatType             string `json:"flat_type"`               // Тип квартиры (сокращенный)
	FlatTypeFull         string `json:"flat_type_full"`          // Тип квартиры
	Flat                 string `json:"flat"`                    // Квартира
	FlatArea             string `json:"flat_area"`               // Площадь квартиры
	SquareMeterPrice     string `json:"square_meter_price"`      // Рыночная стоимость м²
	FlatPrice            string `json:"flat_price"`              // Рыночная стоимость квартиры
	PostalBox            string `json:"postal_box"`              // Абонентский ящик
	FiasID               string `json:"fias_id"`                 // Код ФИАС
	FiasLevel            string `json:"fias_level"`              // Уровень детализации, до которого адрес найден в ФИАС
	KladrID              string `json:"kladr_id"`                // Код КЛАДР
	CapitalMarker        string `json:"capital_marker"`          // Статус центра
	Okato                string `json:"okato"`                   // Код ОКАТО
	Oktmo                string `json:"oktmo"`                   // Код ОКТМО
	TaxOffice            string `json:"tax_office"`              // Код ИФНС для физических лиц
	Timezone             string `json:"timezone"`                // Часовой пояс
	GeoLat               string `json:"geo_lat"`                 // Координаты: широта
	GeoLon               string `json:"geo_lon"`                 // Координаты: долгота
	BeltwayHit           string `json:"beltway_hit"`             // Внутри кольцевой?
	BeltwayDistance      string `json:"beltway_distance"`        // Расстояние от кольцевой в км.

	// TODO: Переделать на собственный тип с кастомный unmarshaller поинмающий как string так и int типы
	// QualityCodeGeo для clean вызовов он int для suggest в адресе банков он string поэтому в поле поставил interface{} чтобы работало и там и там)\
	QualityCodeGeo interface{} `json:"qc_geo"` // Код точности координат
	// TODO: Переделать на собственный тип с кастомный unmarshaller поинмающий как string так и int типы
	// QualityCodeComplete для clean вызовов он int для suggest в адресе банков он string поэтому в поле поставил interface{} чтобы работало и там и там)\
	QualityCodeComplete interface{} `json:"qc_complete"` // Код полноты
	// TODO: Переделать на собственный тип с кастомный unmarshaller поинмающий как string так и int типы
	// QualityCodeHouse для clean вызовов он int для suggest в адресе банков он string поэтому в поле поставил interface{} чтобы работало и там и там)\
	QualityCodeHouse interface{} `json:"qc_house"` // Код проверки дома
	// TODO: Переделать на собственный тип с кастомный unmarshaller поинмающий как string так и int типы
	// QualityCode для clean вызовов он int для suggest в адресе банков он string поэтому в поле поставил interface{} чтобы работало и там и там)\
	QualityCode interface{} `json:"qc"` // Код качества

	UnparsedParts string  `json:"unparsed_parts"` // Нераспознанная часть адреса. Для адреса
	Metro         []Metro `json:"metro"`
}

Address base struct for datdata.Address

type AddressGeoLocator

type AddressGeoLocator interface {
	GeolocateAddress(req GeolocateRequest) ([]ResponseAddress, error)
	GeolocateAddressWithCtx(ctx context.Context, req GeolocateRequest) ([]ResponseAddress, error)
}

type AddressSuggester

type AddressSuggester interface {
	SuggestAddresses(requestParams SuggestRequestParams) ([]ResponseAddress, error)
	SuggestAddressesWithCtx(ctx context.Context, requestParams SuggestRequestParams) ([]ResponseAddress, error)
}

AddressSuggester is the interface for suggest Address

type AddressesCleaner

type AddressesCleaner interface {
	CleanAddresses(addresses ...string) ([]Address, error)
	CleanAddressesWithCtx(ctx context.Context, sourceAddresses ...string) ([]Address, error)
}

AddressesCleaner is the interface for cleaning Addresses

type BalanceResponse

type BalanceResponse struct {
	Balance float64 `json:"balance"`
}

BalanceResponse Response of API request

type Balancer

type Balancer interface {
	ProfileBalance() (*BalanceResponse, error)
	ProfileBalanceWithCtx(ctx context.Context) (*BalanceResponse, error)
}

Balancer is an Balance intervace

type Bank

type Bank struct {
	Opf                  OrganizationOPF `json:"opf"`
	Name                 BankName        `json:"name"`
	Bic                  string          `json:"bic"`                   // Банковский идентификационный код (БИК) ЦБ РФ
	Swift                string          `json:"swift"`                 // Банковский идентификационный код в системе SWIFT
	Okpo                 string          `json:"okpo"`                  // Код ОКПО
	CorrespondentAccount string          `json:"correspondent_account"` // Корреспондентский счет в ЦБ РФ
	RegistrationNumber   string          `json:"registration_number"`   // Регистрационный номер в ЦБ РФ
	// Go cannot use recursive types - thats why we need copy paste all fields to Rks
	Rkc struct {
		Opf                  OrganizationOPF   `json:"opf"`
		Name                 BankName          `json:"name"`
		Bic                  string            `json:"bic"`
		Swift                string            `json:"swift"`
		Okpo                 string            `json:"okpo"`
		CorrespondentAccount string            `json:"correspondent_account"`
		RegistrationNumber   string            `json:"registration_number"`
		Rkc                  interface{}       `json:"rkc"`
		Address              ResponseAddress   `json:"address"`
		Phone                string            `json:"phone"`
		State                OrganizationState `json:"state"`
	} `json:"rkc"` // Расчетно-кассовый центр. Объект такой же структуры, как сам банк.
	Address ResponseAddress   `json:"address"` // см ResponseAddress
	Phone   string            `json:"phone"`   // Не заполняется
	State   OrganizationState `json:"state"`
}

Bank base struct for dadata.Bank

type BankName

type BankName struct {
	Payment string `json:"payment"` // Платежное наименование
	Full    string `json:"full"`    // Полное наименование
	Short   string `json:"short"`   // Краткое наименование
}

BankName наименование банка

type BanksSuggester

type BanksSuggester interface {
	SuggestBanks(requestParams SuggestRequestParams) ([]ResponseBank, error)
	SuggestBanksWithCtx(ctx context.Context, requestParams SuggestRequestParams) ([]ResponseBank, error)
}

BanksSuggester is the interface for suggest Banks

type Birthdate

type Birthdate struct {
	Source      string `json:"source"`    // Исходная дата
	Birthdate   string `json:"birthdate"` // Стандартизованная дата
	QualityCode int    `json:"qc"`        // Код качества
}

Birthdate base struct for dadata.Birthdate

type BirthdatesCleaner

type BirthdatesCleaner interface {
	CleanBirthdates(birthdates ...string) ([]Birthdate, error)
	CleanBirthdatesWithCtx(ctx context.Context, sourceBirthdates ...string) ([]Birthdate, error)
}

BirthdatesCleaner is the interface for cleaning Birthdates

type BoundValue

type BoundValue string

BoundValue type wrapper for suggest bounds full documentation https://confluence.hflabs.ru/pages/viewpage.action?pageId=222888017

const (
	SuggestBoundRegion     BoundValue = "region"     // Регион
	SuggestBoundArea       BoundValue = "area"       // Район
	SuggestBoundCity       BoundValue = "city"       // Город
	SuggestBoundSettlement BoundValue = "settlement" // Населенный пункт
	SuggestBoundStreet     BoundValue = "street"     // Улица
	SuggestBoundHouse      BoundValue = "house"      // Дом
)

const for SuggestBound

type ByIDFinder

type ByIDFinder interface {
	AddressByID(id string) (*ResponseAddress, error)
	AddressByIDWithCtx(ctx context.Context, id string) (*ResponseAddress, error)
	AddressesByID(id string) ([]ResponseAddress, error)
	AddressesByIDWithCtx(ctx context.Context, id string) ([]ResponseAddress, error)
}

ByIDFinder interface for return data by id

type Cleaner

Cleaner combine all xxxCleaner interfaces Stubs it for tests

type DaData

type DaData struct {
	// contains filtered or unexported fields
}

DaData client for DaData.ru (https://dadata.ru/)

func NewDaData

func NewDaData(apiKey, secretKey string) *DaData

NewDaData Create new client of DaData. Api and secret keys see on profile page (https://dadata.ru/profile/).

func NewDaDataCustomClient

func NewDaDataCustomClient(apiKey, secretKey string, httpClient *http.Client) *DaData

NewDaDataCustomClient Create new custom client of DaData. By example, this option should be used to Google AppEngine:

ctx := appengine.NewContext(request)
appEngineClient := urlfetch.Client(ctx)
daData:= NewDaDataCustomClient(apiKey, secretKey, appEngineClient)

func (*DaData) AddressByID

func (daData *DaData) AddressByID(id string) (*ResponseAddress, error)

AddressByID find address by Fias or Kladr see full documentation https://confluence.hflabs.ru/pages/viewpage.action?pageId=312016944

Example
daData := NewDaData(os.Getenv("API_KEY"), os.Getenv("SECRET_KEY"))
addr, err := daData.AddressByID("6300000100000")
if err != nil {
	fmt.Println(err)
	return
}

fmt.Printf("City: %s,\nFiasID: %s,\nKladr: %s\n", addr.Data.City, addr.Data.FiasID, addr.Data.KladrID)
Output:

City: Самара,
FiasID: bb035cc3-1dc2-4627-9d25-a1bf2d4b936b,
Kladr: 6300000100000

func (*DaData) AddressByIDWithCtx

func (daData *DaData) AddressByIDWithCtx(ctx context.Context, id string) (address *ResponseAddress, err error)

AddressByIDWithCtx find address by Fias or Kladr see full documentation https://confluence.hflabs.ru/pages/viewpage.action?pageId=312016944

func (*DaData) AddressesByID

func (daData *DaData) AddressesByID(id string) ([]ResponseAddress, error)

AddressesByID find addresses by Fias or Kladr see full documentation https://confluence.hflabs.ru/pages/viewpage.action?pageId=312016944

func (*DaData) AddressesByIDWithCtx

func (daData *DaData) AddressesByIDWithCtx(ctx context.Context, id string) (addresses []ResponseAddress, err error)

AddressesByIDWithCtx find addresses by Fias or Kladr see full documentation https://confluence.hflabs.ru/pages/viewpage.action?pageId=312016944

func (*DaData) CleanAddresses

func (daData *DaData) CleanAddresses(sourceAddresses ...string) ([]Address, error)

CleanAddresses clean all provided addresses Call https://dadata.ru/api/v2/clean/address

Example
daData := NewDaData(os.Getenv("API_KEY"), os.Getenv("SECRET_KEY"))

addresses, err := daData.CleanAddresses("ул.Правды 26", "пер.Расковой 5")

if nil != err {
	fmt.Println(err)
}

for _, address := range addresses {
	fmt.Println(address.StreetTypeFull)
	fmt.Println(address.Street)
	fmt.Println(address.House)
}
Output:

улица
Правды
26
переулок
Расковой
5

func (*DaData) CleanAddressesWithCtx

func (daData *DaData) CleanAddressesWithCtx(ctx context.Context, sourceAddresses ...string) (addresses []Address, err error)

CleanAddressesWithCtx clean all provided addresses Call https://dadata.ru/api/v2/clean/address

func (*DaData) CleanBirthdates

func (daData *DaData) CleanBirthdates(sourceBirthdates ...string) ([]Birthdate, error)

CleanBirthdates clean all provided birthdates Call https://dadata.ru/api/v2/clean/birthdate

func (*DaData) CleanBirthdatesWithCtx

func (daData *DaData) CleanBirthdatesWithCtx(ctx context.Context, sourceBirthdates ...string) (birthdates []Birthdate, err error)

CleanBirthdatesWithCtx clean all provided birthdates Call https://dadata.ru/api/v2/clean/birthdate

func (*DaData) CleanEmails

func (daData *DaData) CleanEmails(sourceEmails ...string) ([]Email, error)

CleanEmails clean all provided emails Call https://dadata.ru/api/v2/clean/email

func (*DaData) CleanEmailsWithCtx

func (daData *DaData) CleanEmailsWithCtx(ctx context.Context, sourceEmails ...string) (emails []Email, err error)

CleanEmailsWithCtx clean all provided emails Call https://dadata.ru/api/v2/clean/email

func (*DaData) CleanNames

func (daData *DaData) CleanNames(sourceNames ...string) ([]Name, error)

CleanNames clean all provided names Call https://dadata.ru/api/v2/clean/name

Example
daData := NewDaData(os.Getenv("API_KEY"), os.Getenv("SECRET_KEY"))

names, err := daData.CleanNames("Алексей Иванов", "Иван Алексеев")
if nil != err {
	fmt.Println(err)
}

for _, name := range names {
	fmt.Println(name.Surname)
	fmt.Println(name.Name)
}
Output:

Иванов
Алексей
Алексеев
Иван

func (*DaData) CleanNamesWithCtx

func (daData *DaData) CleanNamesWithCtx(ctx context.Context, sourceNames ...string) (names []Name, err error)

CleanNamesWithCtx clean all provided names Call https://dadata.ru/api/v2/clean/name

func (*DaData) CleanPassports

func (daData *DaData) CleanPassports(sourcePassports ...string) ([]Passport, error)

CleanPassports clean all provided passports Call https://dadata.ru/api/v2/clean/passport

func (*DaData) CleanPassportsWithCtx

func (daData *DaData) CleanPassportsWithCtx(ctx context.Context, sourcePassports ...string) (passports []Passport, err error)

CleanPassportsWithCtx clean all provided passports Call https://dadata.ru/api/v2/clean/passport

func (*DaData) CleanPhones

func (daData *DaData) CleanPhones(sourcePhones ...string) ([]Phone, error)

CleanPhones clean all provided phones Call https://dadata.ru/api/v2/clean/phone

func (*DaData) CleanPhonesWithCtx

func (daData *DaData) CleanPhonesWithCtx(ctx context.Context, sourcePhones ...string) (phones []Phone, err error)

CleanPhonesWithCtx clean all provided phones Call https://dadata.ru/api/v2/clean/phone

func (*DaData) CleanVehicles

func (daData *DaData) CleanVehicles(sourceVehicles ...string) ([]Vehicle, error)

CleanVehicles clean all provided vehicles Call https://dadata.ru/api/v2/clean/vehicle

func (*DaData) CleanVehiclesWithCtx

func (daData *DaData) CleanVehiclesWithCtx(ctx context.Context, sourceVehicles ...string) (vehicles []Vehicle, err error)

CleanVehiclesWithCtx clean all provided vehicles Call https://dadata.ru/api/v2/clean/vehicle

func (*DaData) DailyStat

func (daData *DaData) DailyStat(date time.Time) (*StatResponse, error)

DailyStat return daily statistics see documentation https://dadata.ru/api/stat/

func (*DaData) DailyStatWithCtx

func (daData *DaData) DailyStatWithCtx(ctx context.Context, date time.Time) (result *StatResponse, err error)

DailyStatWithCtx return daily statistics see documentation https://dadata.ru/api/stat/

func (*DaData) GeoIP

func (daData *DaData) GeoIP(ip string) (*GeoIPResponse, error)

GeoIP try to find address by IP see documentation on:

https://dadata.ru/api/detect_address_by_ip/
https://confluence.hflabs.ru/pages/viewpage.action?pageId=715096277

ip string representation of ip-address (example 10.12.44.23) if ip=="" then dadata try to get ip-address from X-Forwarded-For header

Example
daData := NewDaData(os.Getenv("API_KEY"), os.Getenv("SECRET_KEY"))

geoIPResponse, err := daData.GeoIP("83.220.54.223")
if nil != err {
	fmt.Println(err)
	return
}
if geoIPResponse.Location == nil {
	fmt.Println("empty result from GeoIP")
	return
}
address := geoIPResponse.Location.Data
fmt.Println(address.Country)
fmt.Println(address.City)
fmt.Printf("see on https://www.google.com/maps/@%s,%sf,14z\n", address.GeoLat, address.GeoLon)
Output:

Россия
Москва
see on https://www.google.com/maps/@55.7540471,37.620405f,14z

func (*DaData) GeoIPWithCtx

func (daData *DaData) GeoIPWithCtx(ctx context.Context, ip string) (result *GeoIPResponse, err error)

GeoIPWithCtx try to find address by IP see documentation on:

https://dadata.ru/api/detect_address_by_ip/
https://confluence.hflabs.ru/pages/viewpage.action?pageId=715096277

ip string representation of ip-address (example 10.12.44.23) if ip=="" then dadata try to get ip-address from X-Forwarded-For header

func (*DaData) GeolocateAddress

func (daData *DaData) GeolocateAddress(req GeolocateRequest) ([]ResponseAddress, error)

GeolocateAddress try to find address by coordinates

func (*DaData) GeolocateAddressWithCtx

func (daData *DaData) GeolocateAddressWithCtx(ctx context.Context, req GeolocateRequest) (ret []ResponseAddress, err error)

GeolocateAddressWithCtx try to find address by coordinates

func (*DaData) ProfileBalance

func (daData *DaData) ProfileBalance() (*BalanceResponse, error)

ProfileBalance return daily statistics see documentation https://dadata.ru/api/stat/

func (*DaData) ProfileBalanceWithCtx

func (daData *DaData) ProfileBalanceWithCtx(ctx context.Context) (result *BalanceResponse, err error)

ProfileBalanceWithCtx return daily statistics see documentation https://dadata.ru/api/stat/

func (*DaData) SuggestAddresses

func (daData *DaData) SuggestAddresses(requestParams SuggestRequestParams) ([]ResponseAddress, error)

SuggestAddresses try to return suggest addresses by requestParams

Example
daData := NewDaData(os.Getenv("API_KEY"), os.Getenv("SECRET_KEY"))

addresses, err := daData.SuggestAddresses(SuggestRequestParams{Query: "Преснен", Count: 2})
if nil != err {
	fmt.Println(err)
}

for _, address := range addresses {
	fmt.Println(address.UnrestrictedValue)
	fmt.Println(address.Data.Street)
	fmt.Println(address.Data.FiasLevel)
}
Output:

г Москва, Пресненская наб
Пресненская
7
г Москва, ул Пресненский Вал
Пресненский Вал
7
Example (Granular)
daData := NewDaData(os.Getenv("API_KEY"), os.Getenv("SECRET_KEY"))

var req SuggestRequestParams

req.Query = "лен"

req.Locations = append(req.Locations, SuggestRequestParamsLocation{
	RegionFiasID: "df3d7359-afa9-4aaa-8ff9-197e73906b1c",
	CityFiasID:   "e9e684ce-7d60-4480-ba14-ca6da658188b",
})

req.FromBound = SuggestBound{SuggestBoundStreet}
req.ToBound = SuggestBound{SuggestBoundStreet}

req.RestrictValue = true
req.Count = 2

addresses, err := daData.SuggestAddresses(req)
if nil != err {
	fmt.Println(err)
}

for _, address := range addresses {
	fmt.Println(address.UnrestrictedValue)
	fmt.Println(address.Data.Street)
}
Output:

Самарская обл, г Сызрань, ул Ленина
Ленина
Самарская обл, г Сызрань, ул Ленинградская
Ленинградская

func (*DaData) SuggestAddressesWithCtx

func (daData *DaData) SuggestAddressesWithCtx(ctx context.Context, requestParams SuggestRequestParams) (ret []ResponseAddress, err error)

SuggestAddressesWithCtx try to return suggest addresses by requestParams

Example
daData := NewDaData(os.Getenv("API_KEY"), os.Getenv("SECRET_KEY"))

var req SuggestRequestParams

ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)

req.Query = "лен"

req.Locations = append(req.Locations, SuggestRequestParamsLocation{
	RegionFiasID: "df3d7359-afa9-4aaa-8ff9-197e73906b1c",
	CityFiasID:   "e9e684ce-7d60-4480-ba14-ca6da658188b",
})

req.FromBound = SuggestBound{SuggestBoundStreet}
req.ToBound = SuggestBound{SuggestBoundStreet}

req.RestrictValue = true
req.Count = 2

addresses, err := daData.SuggestAddressesWithCtx(ctx, req)
if nil != err {
	fmt.Println(err)
}

for _, address := range addresses {
	fmt.Println(address.UnrestrictedValue)
}

cancel()
// if ctx is exited (by cancel or timeout) we must catch err
_, err = daData.SuggestAddressesWithCtx(ctx, req)
fmt.Println(err)
Output:

Самарская обл, г Сызрань, ул Ленина
Самарская обл, г Сызрань, ул Ленинградская
sendRequestToURL: ctx.Err return error: context canceled

func (*DaData) SuggestBanks

func (daData *DaData) SuggestBanks(requestParams SuggestRequestParams) ([]ResponseBank, error)

SuggestBanks try to return suggest banks by requestParams

func (*DaData) SuggestBanksWithCtx

func (daData *DaData) SuggestBanksWithCtx(ctx context.Context, requestParams SuggestRequestParams) (ret []ResponseBank, err error)

SuggestBanksWithCtx try to return suggest banks by requestParams

func (*DaData) SuggestEmails

func (daData *DaData) SuggestEmails(requestParams SuggestRequestParams) ([]ResponseEmail, error)

SuggestEmails try to return suggest emails by requestParams

func (*DaData) SuggestEmailsWithCtx

func (daData *DaData) SuggestEmailsWithCtx(ctx context.Context, requestParams SuggestRequestParams) (ret []ResponseEmail, err error)

SuggestEmailsWithCtx try to return suggest emails by requestParams

func (*DaData) SuggestNames

func (daData *DaData) SuggestNames(requestParams SuggestRequestParams) ([]ResponseName, error)

SuggestNames try to return suggest names by requestParams

func (*DaData) SuggestNamesWithCtx

func (daData *DaData) SuggestNamesWithCtx(ctx context.Context, requestParams SuggestRequestParams) (ret []ResponseName, err error)

SuggestNamesWithCtx try to return suggest names by requestParams

func (*DaData) SuggestParties

func (daData *DaData) SuggestParties(requestParams SuggestRequestParams) ([]ResponseParty, error)

SuggestParties try to return suggest parties by requestParams

func (*DaData) SuggestPartiesWithCtx

func (daData *DaData) SuggestPartiesWithCtx(ctx context.Context, requestParams SuggestRequestParams) (ret []ResponseParty, err error)

SuggestPartiesWithCtx try to return suggest parties by requestParams

type Email

type Email struct {
	Source      string `json:"source"` // Исходный e-mail
	Email       string `json:"email"`  // Стандартизованный e-mail
	QualityCode int    `json:"qc"`     // Код качества
}

Email base struct for dadata.Email

type EmailsCleaner

type EmailsCleaner interface {
	CleanEmails(emails ...string) ([]Email, error)
	CleanEmailsWithCtx(ctx context.Context, sourceEmails ...string) ([]Email, error)
}

EmailsCleaner is the interface for cleaning Emails

type EmailsSuggester

type EmailsSuggester interface {
	SuggestEmails(requestParams SuggestRequestParams) ([]ResponseEmail, error)
	SuggestEmailsWithCtx(ctx context.Context, requestParams SuggestRequestParams) ([]ResponseEmail, error)
}

EmailsSuggester is the interface for suggest Emails

type GeoIPDetector

type GeoIPDetector interface {
	GeoIP(ip string) (*GeoIPResponse, error)
	GeoIPWithCtx(ctx context.Context, ip string) (*GeoIPResponse, error)
}

GeoIPDetector is the interface for detect address by client IP

type GeoIPResponse

type GeoIPResponse struct {
	Location *ResponseAddress `json:"location"`
}

GeoIPResponse response for GeoIP

type GeolocateRequest

type GeolocateRequest struct {
	Lat          float32 `json:"lat"`
	Lon          float32 `json:"lon"`
	Count        int     `json:"count,omitempty"`
	RadiusMeters int     `json:"radius_meters,omitempty"`
}

type Metro

type Metro struct {
	Name     string  `json:"name"`
	Line     string  `json:"line"`
	Distance float64 `json:"distance"`
}

Metro base struct for dadata.Metro

type Name

type Name struct {
	Source         string      `json:"source"`          // Исходное ФИО одной строкой
	Result         string      `json:"result"`          // Стандартизованное ФИО одной строкой
	ResultGenitive string      `json:"result_genitive"` // ФИО в родительном падеже (кого?)
	ResultDative   string      `json:"result_dative"`   // ФИО в дательном падеже (кому?)
	ResultAblative string      `json:"result_ablative"` // ФИО в творительном падеже (кем?)
	Surname        string      `json:"surname"`         // Фамилия
	Name           string      `json:"name"`            // Имя
	Patronymic     string      `json:"patronymic"`      // Отчество
	Gender         string      `json:"gender"`          // Пол
	QualityCode    interface{} `json:"qc"`              // Код качества
}

Name base struct for dadata.Name

type NamesCleaner

type NamesCleaner interface {
	CleanNames(names ...string) ([]Name, error)
	CleanNamesWithCtx(ctx context.Context, sourceNames ...string) ([]Name, error)
}

NamesCleaner is the interface for cleaning Names

type NamesSuggester

type NamesSuggester interface {
	SuggestNames(requestParams SuggestRequestParams) ([]ResponseName, error)
	SuggestNamesWithCtx(ctx context.Context, requestParams SuggestRequestParams) ([]ResponseName, error)
}

NamesSuggester is the interface for suggest Names

type OrganizationOPF

type OrganizationOPF struct {
	Type  string `json:"type"`  // Тип кредитной организации
	Full  string `json:"full"`  // Тип кредитной организации (на русском)
	Short string `json:"short"` // Тип кредитной организации (на русском, сокращенный)
}

OrganizationOPF Тип Кредитной организации

type OrganizationState

type OrganizationState struct {
	Status string `json:"status"` //Статус организации:
	//  ACTIVE      — действующая
	//  LIQUIDATING — ликвидируется
	//  LIQUIDATED  — ликвидирована
	ActualityDate    int64  `json:"actuality_date"`    // Дата актуальности сведений
	RegistrationDate int64  `json:"registration_date"` // Дата регистрации
	LiquidationDate  string `json:"liquidation_date"`  // Дата ликвидации
}

OrganizationState Статус организации

type PartiesSuggester

type PartiesSuggester interface {
	SuggestParties(requestParams SuggestRequestParams) ([]ResponseParty, error)
	SuggestPartiesWithCtx(ctx context.Context, requestParams SuggestRequestParams) ([]ResponseParty, error)
}

PartiesSuggester is the interface for suggest Parties

type Party

type Party struct {
	Kpp        string `json:"kpp"`
	Capital    string `json:"capital"`
	Management struct {
		Name string `json:"name"`
		Post string `json:"post"`
	} `json:"management"`
	Founders    string            `json:"founders"`
	Managers    string            `json:"managers"`
	BranchType  string            `json:"branch_type"`
	BranchCount int               `json:"branch_count"`
	Source      string            `json:"source"`
	Qc          string            `json:"qc"`
	Hid         string            `json:"hid"`
	Type        string            `json:"type"`
	State       OrganizationState `json:"state"`
	Opf         OrganizationOPF   `json:"opf"`
	Name        struct {
		FullWithOpf  string `json:"full_with_opf"`
		ShortWithOpf string `json:"short_with_opf"`
		Latin        string `json:"latin"`
		Full         string `json:"full"`
		Short        string `json:"short"`
	} `json:"name"`
	Inn         string          `json:"inn"`
	Ogrn        string          `json:"ogrn"`
	Okpo        string          `json:"okpo"`
	Okved       string          `json:"okved"`
	Okveds      string          `json:"okveds"`
	Authorities string          `json:"authorities"`
	Documents   string          `json:"documents"`
	Licenses    string          `json:"licenses"`
	Address     ResponseAddress `json:"address"`
	Phones      string          `json:"phones"`
	Emails      string          `json:"emails"`
	OgrnDate    int64           `json:"ogrn_date"`
	OkvedType   string          `json:"okved_type"`
}

Party base struct for dadata.Party (rus Организация)

type Passport

type Passport struct {
	Source      string `json:"source"` // Исходная серия и номер одной строкой
	Series      string `json:"series"` // Серия
	Number      string `json:"number"` // Номер
	QualityCode int    `json:"qc"`     // Код проверки
}

Passport base struct for dadata.Passport

type PassportCleaner

type PassportCleaner interface {
	CleanPassports(passports ...string) ([]Passport, error)
	CleanPassportsWithCtx(ctx context.Context, sourcePassports ...string) ([]Passport, error)
}

PassportCleaner is the interface for cleaning Passport

type Phone

type Phone struct {
	Source              string `json:"source"`       // Исходный телефон одной строкой
	Type                string `json:"type"`         // Тип телефона
	Phone               string `json:"phone"`        // Стандартизованный телефон одной строкой
	CountryCode         string `json:"country_code"` // Код страны
	CityCode            string `json:"city_code"`    // Код города / DEF-код
	Number              string `json:"number"`       // Локальный номер телефона
	Extension           string `json:"extension"`    // Добавочный номер
	Provider            string `json:"provider"`     // Оператор связи
	Region              string `json:"region"`       // Регион
	Timezone            string `json:"timezone"`     // Часовой пояс
	QualityCodeConflict int    `json:"qc_conflict"`  // Признак конфликта телефона с адресом
	QualityCode         int    `json:"qc"`           // Код качества
}

Phone base struct for dadata.Phone

type PhonesCleaner

type PhonesCleaner interface {
	CleanPhones(phones ...string) ([]Phone, error)
	CleanPhonesWithCtx(ctx context.Context, sourcePhones ...string) ([]Phone, error)
}

PhonesCleaner is the interface for cleaning phones

type ResponseAddress

type ResponseAddress struct {
	Value             string  `json:"value"`
	UnrestrictedValue string  `json:"unrestricted_value"`
	Data              Address `json:"data"`
}

ResponseAddress api response for address

type ResponseBank

type ResponseBank struct {
	Value             string `json:"value"`
	UnrestrictedValue string `json:"unrestricted_value"`
	Data              Bank   `json:"data"`
}

ResponseBank api response for bank

type ResponseEmail

type ResponseEmail struct {
	Value             string `json:"value"`
	UnrestrictedValue string `json:"unrestricted_value"`
	Data              Email  `json:"data"`
}

ResponseEmail api response for email

type ResponseName

type ResponseName struct {
	Value             string `json:"value"`
	UnrestrictedValue string `json:"unrestricted_value"`
	Data              Name   `json:"data"`
}

ResponseName api response for name

type ResponseParty

type ResponseParty struct {
	Value             string `json:"value"`
	UnrestrictedValue string `json:"unrestricted_value"`
	Data              Party  `json:"data"`
}

ResponseParty api response for party

type StatResponse

type StatResponse struct {
	Date     string `json:"date"`
	Services struct {
		Merging     int `json:"merging"`
		Suggestions int `json:"suggestions"`
		Clean       int `json:"clean"`
	} `json:"services"`
}

StatResponse usage statitics see docs https://dadata.ru/api/stat/

type Stater

type Stater interface {
	DailyStat(date time.Time) (*StatResponse, error)
	DailyStatWithCtx(ctx context.Context, date time.Time) (*StatResponse, error)
}

Stater interface for return daily statistics

type SuggestAddressResponse

type SuggestAddressResponse struct {
	Suggestions []ResponseAddress `json:"suggestions"`
}

SuggestAddressResponse result slice for address suggestions

type SuggestBankResponse

type SuggestBankResponse struct {
	Suggestions []ResponseBank `json:"suggestions"`
}

SuggestBankResponse result slice for bank suggestions

type SuggestBound

type SuggestBound struct {
	Value BoundValue `json:"value"`
}

SuggestBound for granular sugestion full documentation https://confluence.hflabs.ru/pages/viewpage.action?pageId=222888017

type SuggestEmailResponse

type SuggestEmailResponse struct {
	Suggestions []ResponseEmail `json:"suggestions"`
}

SuggestEmailResponse result slice for email suggestions

type SuggestNameResponse

type SuggestNameResponse struct {
	Suggestions []ResponseName `json:"suggestions"`
}

SuggestNameResponse result slice for name suggestions

type SuggestPartyResponse

type SuggestPartyResponse struct {
	Suggestions []ResponseParty `json:"suggestions"`
}

SuggestPartyResponse result slice for party suggestions

type SuggestRequestParams

type SuggestRequestParams struct {
	Query         string                         `json:"query"` // user input for suggestion
	Count         int                            `json:"count"` // ligmit for results
	Locations     []SuggestRequestParamsLocation `json:"locations"`
	RestrictValue bool                           `json:"restrict_value"` // don't show restricts (region) on results

	FromBound SuggestBound `json:"from_bound"`
	ToBound   SuggestBound `json:"to_bound"`
}

SuggestRequestParams Request struct

type SuggestRequestParamsLocation

type SuggestRequestParamsLocation struct {
	FiasID               string `json:"fias_id,omitempty"`
	KladrID              string `json:"kladr_id,omitempty"`
	Region               string `json:"region,omitempty"`
	RegionFiasID         string `json:"region_fias_id,omitempty"`
	RegionKladrID        string `json:"region_kladr_id,omitempty"`
	RegionTypeFull       string `json:"region_type_full,omitempty"`
	City                 string `json:"city,omitempty"`
	CityFiasID           string `json:"city_fias_id,omitempty"` // search only in this area
	CityKladrID          string `json:"city_kladr_id,omitempty"`
	CityTypeFull         string `json:"city_type_full,omitempty"`
	CityDistrictTypeFull string `json:"city_district_type_full,omitempty"`
	Settlement           string `json:"settlement,omitempty"`
	SettlementFiasID     string `json:"settlement_fias_id,omitempty"`
	SettlementKladrID    string `json:"settlement_kladr_id,omitempty"`
	SettlementTypeFull   string `json:"settlement_type_full,omitempty"`
	Street               string `json:"street,omitempty"`
	StreetFiasID         string `json:"street_fias_id,omitempty"`
	StreetKladrID        string `json:"street_kladr_id,omitempty"`
	StreetTypeFull       string `json:"street_type_full,omitempty"`
	AreaTypeFull         string `json:"area_type_full,omitempty"`
}

SuggestRequestParamsLocation constraints for suggestion full documentation https://confluence.hflabs.ru/pages/viewpage.action?pageId=204669108

type Suggester

Suggester combine all xxxSuggester interfaces Stubs it for tests

type Vehicle

type Vehicle struct {
	Source      string `json:"source"` // Исходное значение
	Result      string `json:"result"` // Стандартизованное значение
	Brand       string `json:"brand"`  // Марка
	Model       string `json:"model"`  // Модель
	QualityCode int    `json:"qc"`     // Код проверки
}

Vehicle base struct for dadata.Vehicle

type VehicleCleaner

type VehicleCleaner interface {
	CleanVehicles(vehicles ...string) ([]Vehicle, error)
	CleanVehiclesWithCtx(ctx context.Context, sourceVehicles ...string) ([]Vehicle, error)
}

VehicleCleaner is the interface for cleaning Vehicle

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL