Documentation
¶
Overview ¶
Package nalogo is a Go client for the Russian FNS "Moy Nalog" API (lknpd.nalog.ru) used by self-employed taxpayers.
Index ¶
- Constants
- Variables
- type APIError
- type AtomTime
- type CancelComment
- type CancelResponse
- type ChallengeResponse
- type Client
- func (c *Client) Authenticate(ctx context.Context, tokenJSON string) error
- func (c *Client) CreateAccessToken(ctx context.Context, inn, password string) (string, error)
- func (c *Client) CreateAccessTokenByPhone(ctx context.Context, phone, challengeToken, code string) (string, error)
- func (c *Client) CreatePhoneChallenge(ctx context.Context, phone string) (*ChallengeResponse, error)
- func (c *Client) INN() string
- func (c *Client) Income() *Income
- func (c *Client) PaymentType() *PaymentType
- func (c *Client) Receipt() *Receipt
- func (c *Client) Tax() *Tax
- func (c *Client) User() *User
- type FileStore
- type Income
- func (a *Income) Cancel(ctx context.Context, receiptUUID string, comment CancelComment) (*CancelResponse, error)
- func (a *Income) Create(ctx context.Context, name string, amount MoneyAmount, quantity Quantity) (*IncomeResponse, error)
- func (a *Income) CreateMultipleItems(ctx context.Context, services []IncomeServiceItem, operationTime AtomTime, ...) (*IncomeResponse, error)
- type IncomeClientInfo
- type IncomeResponse
- type IncomeServiceItem
- type IncomeType
- type MaskedString
- type MemoryStore
- type MoneyAmount
- type Option
- type PaymentType
- type PaymentTypeEntry
- type Quantity
- type Receipt
- type Tax
- type TokenData
- type TokenStore
- type User
- type UserProfile
- type UserResponse
Constants ¶
const ( CancelCommentCancel = CancelComment("Чек сформирован ошибочно") CancelCommentRefund = CancelComment("Возврат средств") )
const ( IncomeTypeFromIndividual = IncomeType("FROM_INDIVIDUAL") IncomeTypeFromLegalEntity = IncomeType("FROM_LEGAL_ENTITY") IncomeTypeFromForeignAgency = IncomeType("FROM_FOREIGN_AGENCY") )
Variables ¶
var ( ErrValidation = fmt.Errorf("%w: validation (400)", ErrDomain) ErrForbidden = fmt.Errorf("%w: forbidden (403)", ErrDomain) ErrNotFound = fmt.Errorf("%w: not found (404)", ErrDomain) ErrClient = fmt.Errorf("%w: client error (406)", ErrDomain) ErrPhone = fmt.Errorf("%w: phone error (422)", ErrDomain) ErrServer = fmt.Errorf("%w: server error (500)", ErrDomain) ErrUnknown = fmt.Errorf("%w: unknown error", ErrDomain) ErrNotAuthenticated = fmt.Errorf("%w: not authenticated", ErrDomain) )
HTTP-status sentinels — mirror upstream Python exception hierarchy 1:1.
var ErrDomain = errors.New("nalogo")
ErrDomain is the root sentinel; all library errors wrap it.
Functions ¶
This section is empty.
Types ¶
type APIError ¶
APIError carries the HTTP status code and (masked) response body alongside the appropriate sentinel. It satisfies both errors.Is (via Is) and errors.As (via type assertion) for callers that need status details.
type AtomTime ¶
AtomTime wraps time.Time and serializes to/from the FNS ATOM datetime format.
func AtomTimeNow ¶
func AtomTimeNow() AtomTime
AtomTimeNow returns the current UTC time wrapped in AtomTime.
func (AtomTime) MarshalJSON ¶
func (*AtomTime) UnmarshalJSON ¶
type CancelComment ¶
type CancelComment = string
CancelComment is the cancellation reason wire value (Russian string required by FNS API).
type CancelResponse ¶
CancelResponse is returned by Cancel.
type ChallengeResponse ¶
type ChallengeResponse struct {
ChallengeToken string `json:"challengeToken"`
ExpireDate string `json:"expireDate"`
ExpireIn int `json:"expireIn"`
}
ChallengeResponse is returned by CreatePhoneChallenge.
type Client ¶
type Client struct {
// contains filtered or unexported fields
}
Client is the main facade for the FNS "Мой налог" API. Construct with New; all I/O methods require a context.Context first arg.
func (*Client) Authenticate ¶
Authenticate loads a previously obtained token JSON into the client. After this call, all API requests will use the token.
func (*Client) CreateAccessToken ¶
CreateAccessToken authenticates via INN + password. Returns the raw token JSON string (mirrors upstream). Persists the token to the configured TokenStore.
func (*Client) CreateAccessTokenByPhone ¶
func (c *Client) CreateAccessTokenByPhone(ctx context.Context, phone, challengeToken, code string) (string, error)
CreateAccessTokenByPhone completes SMS authentication. Returns the raw token JSON string. Persists the token to the configured TokenStore.
func (*Client) CreatePhoneChallenge ¶
func (c *Client) CreatePhoneChallenge(ctx context.Context, phone string) (*ChallengeResponse, error)
CreatePhoneChallenge starts the two-step SMS authentication (v2 endpoint).
func (*Client) PaymentType ¶
func (c *Client) PaymentType() *PaymentType
PaymentType returns a PaymentType API accessor.
type FileStore ¶
type FileStore struct {
// contains filtered or unexported fields
}
FileStore is a file-based TokenStore that persists token JSON to disk (mode 0600).
func NewFileStore ¶
NewFileStore creates a FileStore that reads/writes to path.
type Income ¶
type Income struct {
// contains filtered or unexported fields
}
Income is the income-receipt API accessor.
func (*Income) Cancel ¶
func (a *Income) Cancel(ctx context.Context, receiptUUID string, comment CancelComment) (*CancelResponse, error)
Cancel annuls an income receipt. comment must be one of CancelCommentCancel or CancelCommentRefund.
func (*Income) Create ¶
func (a *Income) Create(ctx context.Context, name string, amount MoneyAmount, quantity Quantity) (*IncomeResponse, error)
Create issues a single-item income receipt.
func (*Income) CreateMultipleItems ¶
func (a *Income) CreateMultipleItems(ctx context.Context, services []IncomeServiceItem, operationTime AtomTime, client *IncomeClientInfo) (*IncomeResponse, error)
CreateMultipleItems issues an income receipt with one or more line items. operationTime is the time the service was rendered; pass AtomTimeNow() for "now". client is optional; pass nil for an individual payer (default).
type IncomeClientInfo ¶
type IncomeClientInfo struct {
ContactPhone *string `json:"contactPhone,omitempty"`
DisplayName *string `json:"displayName,omitempty"`
IncomeType IncomeType `json:"incomeType"`
INN *string `json:"inn,omitempty"`
}
IncomeClientInfo carries payer information for an income receipt. For individual clients (default), all fields are optional. For legal entities (IncomeTypeFromLegalEntity), INN and DisplayName are required.
type IncomeResponse ¶
type IncomeResponse struct {
ApprovedReceiptUUID string `json:"approvedReceiptUuid"`
}
IncomeResponse is returned by Create and CreateMultipleItems.
type IncomeServiceItem ¶
type IncomeServiceItem struct {
Name string `json:"name"`
Amount MoneyAmount `json:"amount"`
Quantity Quantity `json:"quantity"`
}
IncomeServiceItem represents one line item in an income receipt.
type MaskedString ¶
type MaskedString string
MaskedString is a string whose slog representation is always "***". Use it for INN, phone numbers, tokens, and passwords in log records.
func (MaskedString) LogValue ¶
func (m MaskedString) LogValue() slog.Value
type MemoryStore ¶
type MemoryStore struct {
// contains filtered or unexported fields
}
MemoryStore is a thread-safe in-memory TokenStore (default).
type MoneyAmount ¶
MoneyAmount wraps decimal.Decimal and serializes to/from a JSON quoted string (e.g. "100.50") as required by the FNS API.
func MustMoneyAmount ¶
func MustMoneyAmount(s string) MoneyAmount
MustMoneyAmount constructs a MoneyAmount from a decimal string and panics on error. For use in tests and compile-time constants only.
func NewMoneyAmount ¶
func NewMoneyAmount(s string) (MoneyAmount, error)
NewMoneyAmount constructs a MoneyAmount from a decimal string (e.g. "100.50").
func (MoneyAmount) MarshalJSON ¶
func (m MoneyAmount) MarshalJSON() ([]byte, error)
func (*MoneyAmount) UnmarshalJSON ¶
func (m *MoneyAmount) UnmarshalJSON(data []byte) error
type Option ¶
type Option func(*config)
Option mutates the client configuration.
func WithBaseURL ¶
WithBaseURL overrides the FNS API base URL (default: https://lknpd.nalog.ru/api).
func WithDeviceID ¶
WithDeviceID sets the device ID sent in every auth request.
func WithHTTPClient ¶
WithHTTPClient provides a custom base Transport for internal clients. If cl and cl.Transport are non-nil, the transport is used as the base for authTransport; auth refresh behavior remains enabled.
func WithLogger ¶
WithLogger sets the structured logger (default: slog.Default()).
func WithTimeout ¶
WithTimeout sets the HTTP client timeout (default: 10s).
func WithTokenStore ¶
func WithTokenStore(s TokenStore) Option
WithTokenStore plugs in a custom TokenStore (default: MemoryStore).
type PaymentType ¶
type PaymentType struct {
// contains filtered or unexported fields
}
PaymentType is the payment-type API accessor.
func (*PaymentType) Favorite ¶
func (p *PaymentType) Favorite(ctx context.Context) (*PaymentTypeEntry, error)
Favorite returns the first payment type marked as favorite, or nil if none.
func (*PaymentType) Table ¶
func (p *PaymentType) Table(ctx context.Context) ([]PaymentTypeEntry, error)
Table returns all available payment types.
type PaymentTypeEntry ¶
type PaymentTypeEntry struct {
ID string `json:"id"`
Name string `json:"name"`
Favorite bool `json:"favorite"`
Extra map[string]any `json:"-"`
}
PaymentTypeEntry is a single entry from GET /v1/payment-type/table.
type Quantity ¶ added in v0.1.1
Quantity wraps decimal.Decimal and represents a service unit count in an income receipt. It serializes identically to MoneyAmount (JSON quoted string, 2 decimal places) but is a distinct type to prevent accidental interchange with monetary amounts.
func MustQuantity ¶ added in v0.1.1
MustQuantity constructs a Quantity from a decimal string and panics on error. For use in tests and compile-time constants only.
func NewQuantity ¶ added in v0.1.1
NewQuantity constructs a Quantity from a decimal string (e.g. "1", "2.5").
func (Quantity) MarshalJSON ¶ added in v0.1.1
func (*Quantity) UnmarshalJSON ¶ added in v0.1.1
type Receipt ¶
type Receipt struct {
// contains filtered or unexported fields
}
Receipt is the receipt API accessor.
type Tax ¶
type Tax struct {
// contains filtered or unexported fields
}
Tax is the tax API accessor.
type TokenData ¶
type TokenData struct {
Token string `json:"token"`
RefreshToken string `json:"refreshToken"`
TokenExpireIn json.RawMessage `json:"tokenExpireIn,omitempty"`
RefreshTokenExpiresIn json.RawMessage `json:"refreshTokenExpiresIn,omitempty"`
Profile UserProfile `json:"profile"`
}
TokenData is the token payload persisted by TokenStore implementations. TokenExpireIn and RefreshTokenExpiresIn are strings in the FNS API response (ISO datetime or null); leave as json.RawMessage to tolerate both.
type TokenStore ¶
type TokenStore interface {
Save(ctx context.Context, t *TokenData) error
Load(ctx context.Context) (*TokenData, error)
Clear(ctx context.Context) error
}
TokenStore is the persistence port for token data. Implement to swap between storage backends.
type User ¶
type User struct {
// contains filtered or unexported fields
}
User is the user API accessor.
type UserProfile ¶
UserProfile holds the minimal user data returned alongside an access token.