Documentation
¶
Overview ¶
Package ggsel — неофициальный клиент Seller API GGSel.
Дедлайн запроса — более раннее из context вызывающего кода и Timeout клиента. Если HTTP-клиент не передан, Timeout равен 30 секундам. Общий apilogin не наследует отмену другого вызова. Дедлайн этого входа — более раннее из дедлайна context, который его начал, и Timeout клиента. Нулевой Timeout не оставляет вход без границы: тогда предел те же 30 секунд.
Логический отказ v1 — это APIError со статусом пришедшего ответа, в том числе 200. IsUnauthorized к такому отказу не относится.
Повторяются только помеченные безопасные GET. 401 и отказ apilogin не повторяются.
Index ¶
- Constants
- Variables
- func IsUnauthorized(err error) bool
- func Ptr[T any](v T) *T
- type APIError
- type APIErrorEntity
- type APIErrorItem
- type AsyncJob
- type AsyncJobStatus
- type Balance
- type Buyer
- type CatalogCategory
- type CatalogCategoryPage
- type CatalogProduct
- type CatalogProductPage
- type Category
- type CategoryPage
- type CategoryPageParams
- type Chat
- type ChatPage
- type Client
- func (c *Client) ActivateOffers(ctx context.Context, offerIDs []int64) (Job, error)
- func (c *Client) ArchiveOfferOptions(ctx context.Context, offerID int64, body OptionArchive) (Job, error)
- func (c *Client) ArchiveOfferProducts(ctx context.Context, offerID int64, body ProductArchive) (Job, error)
- func (c *Client) ArchiveOfferVariants(ctx context.Context, offerID, optionID int64, body VariantArchive) (Job, error)
- func (c *Client) ArchiveSplittedProducts(ctx context.Context, offerID, variantID int64, body ProductArchive) (Job, error)
- func (c *Client) CheckUniqueCode(ctx context.Context, code string) (UniqueCode, error)
- func (c *Client) CreateOffer(ctx context.Context, body OfferWrite) (Offer, error)
- func (c *Client) CreateOfferOptions(ctx context.Context, offerID int64, options []OfferOptionWrite) ([]OfferOption, error)
- func (c *Client) CreateOfferProducts(ctx context.Context, offerID int64, products []OfferProductInput) error
- func (c *Client) CreateSplittedProducts(ctx context.Context, offerID, variantID int64, products []OfferProductInput) error
- func (c *Client) DeleteOffers(ctx context.Context, offerIDs []int64) (Job, error)
- func (c *Client) GetAsyncJob(ctx context.Context, jobID string) (AsyncJob, error)
- func (c *Client) GetBalance(ctx context.Context) (Balance, error)
- func (c *Client) GetCatalogProduct(ctx context.Context, productID string) (ProductCard, error)
- func (c *Client) GetOffer(ctx context.Context, id int64) (Offer, error)
- func (c *Client) GetOfferOption(ctx context.Context, offerID, optionID int64) (OfferOption, error)
- func (c *Client) GetOrder(ctx context.Context, invoiceID int64) (Order, error)
- func (c *Client) GetProductTask(ctx context.Context, taskID string) (ProductTask, error)
- func (c *Client) ListCatalogCategories(ctx context.Context, params ListCatalogCategoriesParams) (CatalogCategoryPage, error)
- func (c *Client) ListCatalogProducts(ctx context.Context, params ListCatalogProductsParams) (CatalogProductPage, error)
- func (c *Client) ListCategories(ctx context.Context, params ListCategoriesParams) (CategoryPage, error)
- func (c *Client) ListChats(ctx context.Context, params ListChatsParams) (ChatPage, error)
- func (c *Client) ListLastSales(ctx context.Context, params ListLastSalesParams) ([]LastSale, error)
- func (c *Client) ListMessages(ctx context.Context, invoiceID int64, params ListMessagesParams) ([]Message, error)
- func (c *Client) ListOfferOptions(ctx context.Context, offerID int64) (OfferOptionPage, error)
- func (c *Client) ListOfferProducts(ctx context.Context, offerID int64, params ListOfferProductsParams) (OfferProductPage, error)
- func (c *Client) ListOffers(ctx context.Context, params ListOffersParams) (OfferPage, error)
- func (c *Client) ListReceipts(ctx context.Context, params ListReceiptsParams) (ReceiptPage, error)
- func (c *Client) ListReviews(ctx context.Context, params ListReviewsParams) (ReviewPage, error)
- func (c *Client) ListSellerGoods(ctx context.Context, query SellerGoodsQuery) (SellerGoods, error)
- func (c *Client) ListSplittedProducts(ctx context.Context, offerID, variantID int64, params ListOfferProductsParams) (OfferProductPage, error)
- func (c *Client) Login(ctx context.Context) error
- func (c *Client) PauseOffers(ctx context.Context, offerIDs []int64) (Job, error)
- func (c *Client) SearchCategories(ctx context.Context, query string, params CategoryPageParams) (CategoryPage, error)
- func (c *Client) SendMessage(ctx context.Context, invoiceID int64, text string) error
- func (c *Client) UpdateOffer(ctx context.Context, id int64, body OfferWrite) (Offer, error)
- func (c *Client) UpdateOfferOptionVisibility(ctx context.Context, offerID int64, options []OptionVisibility) ([]OfferOption, error)
- func (c *Client) UpdateOfferVariantVisibility(ctx context.Context, offerID, optionID int64, variants []VariantVisibility) ([]OfferVariant, error)
- func (c *Client) UpdateProductPrices(ctx context.Context, changes []ProductPriceChange) (string, error)
- func (c *Client) UpsertOfferVariants(ctx context.Context, offerID, optionID int64, variants []OfferVariantWrite) ([]OfferVariant, error)
- func (c *Client) WalkCategoryPages(ctx context.Context, params ListCategoriesParams, maxPages int, ...) error
- func (c *Client) WalkCategorySearch(ctx context.Context, query string, params CategoryPageParams, maxPages int, ...) error
- func (c *Client) WalkOfferPages(ctx context.Context, params ListOffersParams, maxPages int, ...) error
- type Currency
- type Decimal
- type DeleteAll
- type Delivery
- type DiscountType
- type FeedbackType
- type GoodsCurrency
- type GoodsOrder
- type ImpactType
- type InvoiceState
- type Job
- type Lang
- type LastSale
- type LastSaleProduct
- type ListCatalogCategoriesParams
- type ListCatalogProductsParams
- type ListCategoriesParams
- type ListChatsParams
- type ListLastSalesParams
- type ListMessagesParams
- type ListOfferProductsParams
- type ListOffersParams
- type ListReceiptsParams
- type ListReviewsParams
- type LocalizedText
- type Message
- type MoneyTrio
- type NotificationMethod
- type NotificationSettings
- type NotificationSettingsWrite
- type NotificationType
- type Offer
- type OfferListStatus
- type OfferOption
- type OfferOptionPage
- type OfferOptionStatus
- type OfferOptionType
- type OfferOptionWrite
- type OfferPage
- type OfferProduct
- type OfferProductInput
- type OfferProductPage
- type OfferProductStatus
- type OfferSort
- type OfferStatus
- type OfferSummary
- type OfferVariant
- type OfferVariantWrite
- type OfferWrite
- type OptionArchive
- type OptionVisibility
- type Options
- type Order
- type OrderCodeState
- type OrderFeedback
- type OrderOption
- type Pagination
- type PayCurrency
- type PayLimit
- type PayMethod
- type PrePaymentSettings
- type PrePaymentSettingsWrite
- type PriceChangeType
- type ProductArchive
- type ProductCard
- type ProductCrumb
- type ProductImage
- type ProductOption
- type ProductOptionVariant
- type ProductPriceChange
- type ProductPrices
- type ProductSeller
- type ProductStats
- type ProductTask
- type ProductTaskError
- type ProductTaskStatus
- type ProductUnit
- type Receipt
- type ReceiptCodeFilter
- type ReceiptOperation
- type ReceiptPage
- type ReceiptProduct
- type ReceiptType
- type Review
- type ReviewFilter
- type ReviewPage
- type SaleInfo
- type SellerGoods
- type SellerGoodsQuery
- type SortDirection
- type UniqueCode
- type UniqueCodeOption
- type UniqueCodeState
- type VariantArchive
- type VariantPriceChange
- type VariantVisibility
Examples ¶
Constants ¶
const (
// DefaultBaseURL — база Seller API, если Options.BaseURL пуст.
DefaultBaseURL = "https://seller.ggsel.com"
)
Variables ¶
var ErrPageLimit = errors.New("page limit reached")
ErrPageLimit — обход остановился: HasNextPage всё ещё true, а maxPages уже выбран.
var ErrSellerIDRequired = errors.New("seller id is required")
ErrSellerIDRequired возвращается, если метод v1 вызван без SellerID. Префикс ggsel: добавляет обёртка, не сам sentinel.
Functions ¶
func IsUnauthorized ¶
IsUnauthorized сообщает, что API ответил HTTP 401.
Types ¶
type APIError ¶
type APIError struct {
StatusCode int
Method string
Path string
Body []byte
RetVal *int
RetDesc string
Desc string
Errors []APIErrorItem
}
APIError — ответ Seller API, который не разобран как успех. Error не содержит тело, ключ и token. Тело лежит в Body.
type APIErrorEntity ¶
APIErrorEntity — объект entity у ошибки v2.
type APIErrorItem ¶
type APIErrorItem struct {
Code string
Entity *APIErrorEntity
}
APIErrorItem — элемент errors[] контура v2.
type AsyncJob ¶ added in v1.1.0
type AsyncJob struct {
ID string `json:"job_id"`
Status AsyncJobStatus `json:"status"`
Results json.RawMessage `json:"results"`
}
AsyncJob — результат GET /api_sellers/v2/async_job_results/{job_id}. Results остаётся сырым JSON: у разных операций разная форма, и числа не становятся float64.
type AsyncJobStatus ¶ added in v1.1.0
type AsyncJobStatus string
AsyncJobStatus — состояние результата v2.
const ( AsyncJobPending AsyncJobStatus = "pending" AsyncJobCompleted AsyncJobStatus = "completed" AsyncJobFailed AsyncJobStatus = "failed" )
type Balance ¶ added in v1.1.0
type Balance struct {
Locked *Decimal `json:"amount_t_lock"`
Free *Decimal `json:"amount_t_free"`
Plus *Decimal `json:"amount_t_plus"`
}
Balance — свободные, заблокированные и плюсовые суммы счёта.
type Buyer ¶
type Buyer struct {
PaymentMethod string `json:"payment_method"`
Account string `json:"account"`
Email *string `json:"email"`
Phone *string `json:"phone"`
Skype *string `json:"skype"`
WhatsApp *string `json:"whatsapp"`
IPAddress *string `json:"ip_address"`
PaymentAggregator string `json:"payment_aggregator"`
}
type CatalogCategory ¶ added in v1.1.0
type CatalogCategory struct {
ID int64 `json:"id"`
Name string `json:"name"`
Children []int64 `json:"sub"`
Count *int64 `json:"cnt"`
}
CatalogCategory — категория v1.
type CatalogCategoryPage ¶ added in v1.1.0
type CatalogCategoryPage struct {
Categories []CatalogCategory
}
CatalogCategoryPage — страница категорий v1.
type CatalogProduct ¶ added in v1.1.0
type CatalogProduct struct {
ID int64 `json:"id_goods"`
Name string `json:"name_goods"`
Info string `json:"info_goods"`
Price string `json:"price"`
Currency string `json:"currency"`
AddInfo *string `json:"add_info"`
SellCount int64 `json:"cnt_sell"`
ReturnCount int64 `json:"cnt_return"`
GoodResponses int64 `json:"cnt_goodresponses"`
BadResponses int64 `json:"cnt_badresponses"`
PriceUSD Decimal `json:"price_usd"`
PriceEUR Decimal `json:"price_eur"`
PriceUAH *Decimal `json:"price_uah"`
PriceRUR Decimal `json:"price_rur"`
InStock int64 `json:"in_stock"`
NumInStock int64 `json:"num_in_stock"`
Visible int64 `json:"visible"`
AgentFee *string `json:"commiss_agent"`
HasDiscount *bool `json:"has_discount"`
OptionCount int64 `json:"num_options"`
Sale SaleInfo `json:"sale_info"`
}
CatalogProduct — строка списка товаров v1 и товаров продавца.
type CatalogProductPage ¶ added in v1.1.0
type CatalogProductPage struct {
Page int64
Count int64
HasNextPage bool
HasPreviousPage bool
TotalCount int64
TotalPages int64
Products []CatalogProduct
}
CatalogProductPage — страница списка товаров v1.
type Category ¶
type Category struct {
ID int64 `json:"id"`
Title string `json:"title"`
ContentType string `json:"content_type"`
Fee Decimal `json:"fee"`
PaymentFee Decimal `json:"payment_fee"`
Tree string `json:"tree"`
HasChildren bool `json:"has_children"`
}
Category — категория v2. Fee и PaymentFee — доли комиссии, не float64.
type CategoryPage ¶
type CategoryPage struct {
Categories []Category
Pagination Pagination
}
CategoryPage — одна страница категорий.
type CategoryPageParams ¶
CategoryPageParams — page и limit. Нулевые указатели в запрос не попадают.
type Chat ¶
type Chat struct {
InvoiceID int64 `json:"id_i"`
Email string `json:"email"`
ProductID int64 `json:"product"`
// LastMessageAt — метка времени последнего сообщения. В снимке это строка date_time, не текст реплики.
LastMessageAt string `json:"last_message"`
MessageCount *int64 `json:"cnt_msg"`
NewCount *int64 `json:"cnt_new"`
}
type Client ¶
type Client struct {
// contains filtered or unexported fields
}
Client вызывает Seller API. Его можно использовать из нескольких горутин. New не ходит в сеть.
func New ¶
New собирает клиент. Пустой ключ — ошибка. SellerID может быть нулём: он нужен только методам контура v1.
Example ¶
package main
import (
"github.com/Zoomish/go-ggsel-api"
)
func main() {
if _, err := ggsel.New(ggsel.Options{}); err == nil {
panic("empty key")
}
client, err := ggsel.New(ggsel.Options{APIKey: "test-key"})
if err != nil || client == nil {
panic(err)
}
}
Output:
func (*Client) ActivateOffers ¶ added in v1.1.0
ActivateOffers ставит офферы в продажу. В пачке не больше 100 id.
func (*Client) ArchiveOfferOptions ¶ added in v1.1.0
func (c *Client) ArchiveOfferOptions(ctx context.Context, offerID int64, body OptionArchive) (Job, error)
ArchiveOfferOptions ставит опции в архив и возвращает job. Клиент job не опрашивает.
func (*Client) ArchiveOfferProducts ¶ added in v1.1.0
func (c *Client) ArchiveOfferProducts(ctx context.Context, offerID int64, body ProductArchive) (Job, error)
ArchiveOfferProducts архивирует ключи оффера и возвращает job.
func (*Client) ArchiveOfferVariants ¶ added in v1.1.0
func (c *Client) ArchiveOfferVariants(ctx context.Context, offerID, optionID int64, body VariantArchive) (Job, error)
ArchiveOfferVariants ставит варианты в архив. В снимке это асинхронно: метод возвращает job_id и не ждёт завершения.
func (*Client) ArchiveSplittedProducts ¶ added in v1.1.0
func (c *Client) ArchiveSplittedProducts(ctx context.Context, offerID, variantID int64, body ProductArchive) (Job, error)
ArchiveSplittedProducts архивирует ключи варианта и возвращает job.
func (*Client) CheckUniqueCode ¶
func (*Client) CreateOffer ¶
CreateOffer создаёт оффер. Повтор запроса не выполняется.
func (*Client) CreateOfferOptions ¶ added in v1.1.0
func (c *Client) CreateOfferOptions(ctx context.Context, offerID int64, options []OfferOptionWrite) ([]OfferOption, error)
CreateOfferOptions создаёт пачку опций. Повтор запроса не выполняется.
func (*Client) CreateOfferProducts ¶ added in v1.1.0
func (c *Client) CreateOfferProducts(ctx context.Context, offerID int64, products []OfferProductInput) error
CreateOfferProducts создаёт ключи оффера. Успех — ответ 204 без тела.
func (*Client) CreateSplittedProducts ¶ added in v1.1.0
func (c *Client) CreateSplittedProducts(ctx context.Context, offerID, variantID int64, products []OfferProductInput) error
CreateSplittedProducts создаёт ключи варианта. Успех — ответ 204 без тела.
func (*Client) DeleteOffers ¶ added in v1.1.0
DeleteOffers архивирует офферы. В пачке не больше 100 id.
func (*Client) GetAsyncJob ¶ added in v1.1.0
GetAsyncJob возвращает состояние задачи v2. Повтор безопасен. Цикл опроса остаётся у вызывающего кода.
func (*Client) GetBalance ¶ added in v1.1.0
func (*Client) GetCatalogProduct ¶ added in v1.1.0
func (*Client) GetOfferOption ¶ added in v1.1.0
GetOfferOption возвращает одну опцию вместе с остатками вариантов.
func (*Client) GetOrder ¶
GetOrder возвращает заказ по номеру счёта.
Example ¶
package main
import (
"context"
"errors"
"io"
"net/http"
"net/http/httptest"
"github.com/Zoomish/go-ggsel-api"
)
func main() {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/api_sellers/api/apilogin" {
w.Header().Set("Content-Type", "application/json")
_, _ = io.WriteString(w, `{"retval":0,"token":"tok","valid_thru":"2099-01-01T00:00:00Z"}`)
return
}
w.WriteHeader(http.StatusUnauthorized)
_, _ = io.WriteString(w, `{"retval":-1,"retdesc":"no"}`)
}))
defer srv.Close()
client, err := ggsel.New(ggsel.Options{
APIKey: "test-key",
SellerID: 42,
BaseURL: srv.URL,
})
if err != nil {
panic(err)
}
_, err = client.GetOrder(context.Background(), 15)
var apiErr *ggsel.APIError
if !errors.As(err, &apiErr) || apiErr.StatusCode != http.StatusUnauthorized {
panic(err)
}
}
Output:
func (*Client) GetProductTask ¶ added in v1.1.0
GetProductTask возвращает статус массовой правки цен v1.
func (*Client) ListCatalogCategories ¶ added in v1.1.0
func (c *Client) ListCatalogCategories(ctx context.Context, params ListCatalogCategoriesParams) (CatalogCategoryPage, error)
func (*Client) ListCatalogProducts ¶ added in v1.1.0
func (c *Client) ListCatalogProducts(ctx context.Context, params ListCatalogProductsParams) (CatalogProductPage, error)
func (*Client) ListCategories ¶
func (c *Client) ListCategories(ctx context.Context, params ListCategoriesParams) (CategoryPage, error)
ListCategories возвращает одну страницу категорий.
func (*Client) ListLastSales ¶ added in v1.1.0
ListLastSales возвращает последние продажи. Заголовок locale берётся у клиента: в снимке значение по умолчанию ru.
func (*Client) ListMessages ¶
func (c *Client) ListMessages(ctx context.Context, invoiceID int64, params ListMessagesParams) ([]Message, error)
ListMessages возвращает сообщения заказа. Успешный ответ — JSON-массив.
func (*Client) ListOfferOptions ¶ added in v1.1.0
ListOfferOptions возвращает опции оффера, видимые продавцу.
func (*Client) ListOfferProducts ¶ added in v1.1.0
func (c *Client) ListOfferProducts(ctx context.Context, offerID int64, params ListOfferProductsParams) (OfferProductPage, error)
ListOfferProducts возвращает ключи оффера.
func (*Client) ListOffers ¶
ListOffers возвращает одну страницу офферов.
Example ¶
package main
import (
"context"
"io"
"net/http"
"net/http/httptest"
"github.com/Zoomish/go-ggsel-api"
)
func main() {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
_, _ = io.WriteString(w, `{
"data":[{
"id":1,
"status":"active",
"price":19.99,
"currency":"RUB",
"category":{"id":3,"title":"Games","content_type":"key","fee":0,"payment_fee":0,"tree":"Games","has_children":false},
"has_options":false,
"has_products":false,
"has_splitted_products":false,
"cover_image_ru_url":""
}],
"pagination":{"page":1,"limit":100,"has_next_page":false,"has_previous_page":false}
}`)
}))
defer srv.Close()
client, err := ggsel.New(ggsel.Options{APIKey: "test-key", BaseURL: srv.URL})
if err != nil {
panic(err)
}
page, err := client.ListOffers(context.Background(), ggsel.ListOffersParams{})
if err != nil {
panic(err)
}
if len(page.Offers) != 1 || page.Offers[0].Price == nil || page.Offers[0].Price.String() != "19.99" {
panic(page.Offers)
}
}
Output:
func (*Client) ListReceipts ¶ added in v1.1.0
func (c *Client) ListReceipts(ctx context.Context, params ListReceiptsParams) (ReceiptPage, error)
func (*Client) ListReviews ¶ added in v1.1.0
func (c *Client) ListReviews(ctx context.Context, params ListReviewsParams) (ReviewPage, error)
func (*Client) ListSellerGoods ¶ added in v1.1.0
func (c *Client) ListSellerGoods(ctx context.Context, query SellerGoodsQuery) (SellerGoods, error)
ListSellerGoods возвращает товары продавца. Повтор POST не выполняется.
func (*Client) ListSplittedProducts ¶ added in v1.1.0
func (c *Client) ListSplittedProducts(ctx context.Context, offerID, variantID int64, params ListOfferProductsParams) (OfferProductPage, error)
ListSplittedProducts возвращает ключи варианта.
func (*Client) Login ¶
Login получает token v1. Кэш пустеет за 30 секунд до valid_thru. Если valid_thru не разбирается, token этого вызова возвращается, но в кэш не кладётся. Методы v1 вызывают вход сами, если кэш пуст.
func (*Client) PauseOffers ¶ added in v1.1.0
PauseOffers снимает офферы с продажи. В пачке не больше 100 id.
func (*Client) SearchCategories ¶
func (c *Client) SearchCategories(ctx context.Context, query string, params CategoryPageParams) (CategoryPage, error)
SearchCategories ищет категории по q. Пустой запрос не уходит в сеть.
func (*Client) SendMessage ¶
SendMessage отправляет текст в чат заказа. Пустой текст в сеть не уходит.
func (*Client) UpdateOffer ¶
UpdateOffer частично обновляет оффер. Повтор запроса не выполняется.
Example ¶
package main
import (
"context"
"io"
"net/http"
"net/http/httptest"
"strings"
"github.com/Zoomish/go-ggsel-api"
)
func main() {
var raw string
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
buf, err := io.ReadAll(r.Body)
if err != nil {
panic(err)
}
raw = string(buf)
w.Header().Set("Content-Type", "application/json")
_, _ = io.WriteString(w, `{
"data":{
"id":15,"status":"draft","is_autoselling":false,
"title_ru":"","title_en":"","description_ru":"","description_en":"",
"instructions_ru":"","instructions_en":"","cover_image_ru_url":"",
"category":{"id":1,"title":"","content_type":"","fee":0,"payment_fee":0,"tree":"","has_children":false},
"price":19.99,"currency":"RUB","quantity":0,"is_unlimited_quantity":false,
"sold_splitted_products_count":0,"sold_products_count":0,
"in_stock_products_count":0,"in_stock_splitted_products_count":0,
"has_splitted_products":false,"updated_at":"","created_at":""
}
}`)
}))
defer srv.Close()
client, err := ggsel.New(ggsel.Options{APIKey: "test-key", BaseURL: srv.URL})
if err != nil {
panic(err)
}
price, err := ggsel.ParseDecimal("19.99")
if err != nil {
panic(err)
}
if _, err := client.UpdateOffer(context.Background(), 15, ggsel.OfferWrite{
IsAutoselling: ggsel.Ptr(false),
Price: &price,
}); err != nil {
panic(err)
}
if raw != `{"price":19.99,"is_autoselling":false}` || strings.Contains(raw, "title_ru") {
panic(raw)
}
}
Output:
func (*Client) UpdateOfferOptionVisibility ¶ added in v1.1.0
func (c *Client) UpdateOfferOptionVisibility(ctx context.Context, offerID int64, options []OptionVisibility) ([]OfferOption, error)
UpdateOfferOptionVisibility меняет видимость пачки опций.
func (*Client) UpdateOfferVariantVisibility ¶ added in v1.1.0
func (c *Client) UpdateOfferVariantVisibility(ctx context.Context, offerID, optionID int64, variants []VariantVisibility) ([]OfferVariant, error)
UpdateOfferVariantVisibility меняет видимость пачки вариантов.
func (*Client) UpdateProductPrices ¶ added in v1.1.0
func (c *Client) UpdateProductPrices(ctx context.Context, changes []ProductPriceChange) (string, error)
UpdateProductPrices ставит массовую правку цен. Тело — JSON-массив. Метод возвращает taskId и не ждёт задачу.
func (*Client) UpsertOfferVariants ¶ added in v1.1.0
func (c *Client) UpsertOfferVariants(ctx context.Context, offerID, optionID int64, variants []OfferVariantWrite) ([]OfferVariant, error)
UpsertOfferVariants создаёт или обновляет варианты опции.
func (*Client) WalkCategoryPages ¶ added in v1.1.0
func (c *Client) WalkCategoryPages(ctx context.Context, params ListCategoriesParams, maxPages int, fn func(CategoryPage) error) error
WalkCategoryPages вызывает fn для каждой страницы категорий v2, пока HasNextPage. maxPages ограничивает число запросов так же, как в WalkOfferPages.
func (*Client) WalkCategorySearch ¶ added in v1.1.0
func (c *Client) WalkCategorySearch(ctx context.Context, query string, params CategoryPageParams, maxPages int, fn func(CategoryPage) error) error
WalkCategorySearch вызывает fn для каждой страницы поиска категорий, пока HasNextPage. maxPages ограничивает число запросов так же, как в WalkOfferPages.
func (*Client) WalkOfferPages ¶ added in v1.1.0
func (c *Client) WalkOfferPages(ctx context.Context, params ListOffersParams, maxPages int, fn func(OfferPage) error) error
WalkOfferPages вызывает fn для каждой страницы офферов, пока HasNextPage. maxPages — сколько страниц можно запросить. Ноль и меньше в сеть не уходят. Если после последней разрешённой страницы следующая всё ещё есть, возвращается ErrPageLimit. total_pages не используется. Page в params задаёт первую страницу, по умолчанию 1.
type Currency ¶
type Currency string
Currency — валюта цены оффера v2. В спецификации это RUB.
const (
CurrencyRUB Currency = "RUB"
)
type Decimal ¶
type Decimal struct {
// contains filtered or unexported fields
}
Decimal — точное десятичное число для полей schema type number. В JSON это число, не строка и не float64. null в значении — ошибка разбора. null в *Decimal оставляет указатель nil.
func ParseDecimal ¶ added in v1.1.0
ParseDecimal собирает Decimal из десятичной строки. Методы shopspring наружу не выходят.
func (Decimal) MarshalJSON ¶
func (*Decimal) UnmarshalJSON ¶
type DeleteAll ¶ added in v1.1.0
type DeleteAll string
DeleteAll — строковый флаг архивации. В снимке это "true" или "false", не boolean.
type DiscountType ¶ added in v1.1.0
type DiscountType string
DiscountType — как вариант меняет цену.
const ( DiscountFixed DiscountType = "fixed" DiscountPercent DiscountType = "percent" )
type FeedbackType ¶
type FeedbackType string
FeedbackType — тип отзыва покупателя.
const ( FeedbackPositive FeedbackType = "positive" FeedbackNegative FeedbackType = "negative" )
type GoodsCurrency ¶ added in v1.1.0
type GoodsCurrency string
GoodsCurrency — валюта списка товаров продавца.
const ( GoodsCurrencyUSD GoodsCurrency = "USD" GoodsCurrencyEUR GoodsCurrency = "EUR" GoodsCurrencyRUB GoodsCurrency = "RUB" )
type GoodsOrder ¶ added in v1.1.0
type GoodsOrder string
GoodsOrder — колонка сортировки товаров продавца.
const (
GoodsOrderSales GoodsOrder = "cntsell"
)
type ImpactType ¶ added in v1.1.0
type ImpactType string
ImpactType — направление изменения цены варианта.
const ( ImpactIncrease ImpactType = "increase" ImpactDecrease ImpactType = "decrease" )
type InvoiceState ¶
type InvoiceState int
InvoiceState — состояние счёта v1.
const ( InvoiceStateCreated InvoiceState = 1 InvoiceStateCanceled InvoiceState = 2 InvoiceStatePaid InvoiceState = 3 InvoiceStateCompleted InvoiceState = 4 InvoiceStateRefunded InvoiceState = 5 )
type Lang ¶ added in v1.1.0
type Lang string
Lang — язык заголовков v1. Это ru-RU и en-US, не locale клиента.
type LastSale ¶ added in v1.1.0
type LastSale struct {
InvoiceID int64 `json:"invoice_id"`
Date string `json:"date"`
Product LastSaleProduct `json:"product"`
}
LastSale — одна из последних продаж.
type LastSaleProduct ¶ added in v1.1.0
type LastSaleProduct struct {
ID int64 `json:"id"`
Name string `json:"name"`
PriceRUB Decimal `json:"price_rub"`
PriceUSD Decimal `json:"price_usd"`
PriceEUR Decimal `json:"price_eur"`
PriceUAH *Decimal `json:"price_uah"`
}
LastSaleProduct — товар в последней продаже.
type ListCatalogCategoriesParams ¶ added in v1.1.0
ListCatalogCategoriesParams — страница категорий. Page и Count обязательны.
type ListCatalogProductsParams ¶ added in v1.1.0
ListCatalogProductsParams — фильтр списка товаров. Page и Count обязательны.
type ListCategoriesParams ¶
ListCategoriesParams — фильтр списка категорий.
type ListChatsParams ¶
type ListChatsParams struct {
FilterNew *int64
Email *string
GoodsID *string
PageSize *int64
Page *int64
}
ListChatsParams — фильтр чатов. Нулевые указатели в запрос не попадают.
type ListLastSalesParams ¶ added in v1.1.0
ListLastSalesParams — фильтр последних продаж. Нулевые указатели в запрос не попадают.
type ListMessagesParams ¶
ListMessagesParams — окно сообщений. id_i задаёт метод.
type ListOfferProductsParams ¶ added in v1.1.0
type ListOfferProductsParams struct {
Status *OfferProductStatus
SortColumn *string
SortDirection *string
}
ListOfferProductsParams — фильтр склада. Нулевые указатели в запрос не попадают.
type ListOffersParams ¶
type ListOffersParams struct {
Page *int64
Limit *int64
Search *string
CategoryID *int64
Status *OfferListStatus
Sort *OfferSort
Delivery *Delivery
UpdatedAtFrom *time.Time
}
ListOffersParams — фильтр списка. Нулевые указатели в запрос не попадают.
type ListReceiptsParams ¶ added in v1.1.0
type ListReceiptsParams struct {
Page int64
Count int64
Currency *string
Type *ReceiptType
CodeFilter *ReceiptCodeFilter
AllowType *string
Start *string
Finish *string
}
ListReceiptsParams — фильтр чеков. Page и Count обязательны.
type ListReviewsParams ¶ added in v1.1.0
type ListReviewsParams struct {
Lang Lang
Type *ReviewFilter
Page int64
Count int64
ProductID *int64
}
ListReviewsParams — фильтр отзывов. Page и Count обязательны. Lang пустой становится ru-RU: заголовок locale здесь не совпадает с locale клиента.
type LocalizedText ¶ added in v1.1.0
type Message ¶
type Message struct {
ID int64 `json:"id"`
Text string `json:"message"`
// IsFromBuyer и IsFromSeller — флаги «сообщение от покупателя / продавца», не идентификаторы.
IsFromBuyer int64 `json:"buyer"`
IsFromSeller int64 `json:"seller"`
Deleted *int64 `json:"deleted"`
DateWritten string `json:"date_written"`
DateSeen *string `json:"date_seen"`
IsFile *int64 `json:"is_file"`
Filename *string `json:"filename"`
URL *string `json:"url"`
IsImage *int64 `json:"is_img"`
Preview *string `json:"preview"`
}
type MoneyTrio ¶ added in v1.1.0
type MoneyTrio struct {
RUB *Decimal `json:"RUB"`
USD *Decimal `json:"USD"`
EUR *Decimal `json:"EUR"`
}
MoneyTrio — цены RUB, USD и EUR.
type NotificationMethod ¶
type NotificationMethod string
NotificationMethod — HTTP-метод уведомления.
const ( NotificationMethodGET NotificationMethod = "GET" NotificationMethodPOST NotificationMethod = "POST" )
type NotificationSettings ¶
type NotificationSettings struct {
Type *NotificationType `json:"type"`
URL *string `json:"url"`
Email *string `json:"email"`
HTTPMethod *NotificationMethod `json:"http_method"`
IsDisabled bool `json:"is_disabled"`
IsDefault bool `json:"is_default"`
}
NotificationSettings — уведомление продавца о новом заказе.
type NotificationSettingsWrite ¶
type NotificationSettingsWrite struct {
Type *NotificationType `json:"type,omitempty"`
URL *string `json:"url,omitempty"`
Email *string `json:"email,omitempty"`
HTTPMethod *NotificationMethod `json:"http_method,omitempty"`
IsDisabled *bool `json:"is_disabled,omitempty"`
IsDefault *bool `json:"is_default,omitempty"`
}
NotificationSettingsWrite — частичные настройки уведомления о заказе.
type NotificationType ¶
type NotificationType string
NotificationType — канал уведомления продавца о заказе.
const ( NotificationEmail NotificationType = "email" NotificationURL NotificationType = "url" )
type Offer ¶
type Offer struct {
ID int64 `json:"id"`
Status OfferStatus `json:"status"`
IsAutoselling bool `json:"is_autoselling"`
Delivery *Delivery `json:"delivery"`
TitleRU string `json:"title_ru"`
TitleEN string `json:"title_en"`
DescriptionRU string `json:"description_ru"`
DescriptionEN string `json:"description_en"`
InstructionsRU string `json:"instructions_ru"`
InstructionsEN string `json:"instructions_en"`
CoverImageRUURL string `json:"cover_image_ru_url"`
CoverImageENURL *string `json:"cover_image_en_url"`
Category Category `json:"category"`
Price Decimal `json:"price"`
Currency Currency `json:"currency"`
Quantity int64 `json:"quantity"`
IsUnlimitedQuantity bool `json:"is_unlimited_quantity"`
MinQuantity *int64 `json:"min_quantity"`
MaxQuantity *int64 `json:"max_quantity"`
SoldSplittedProductsCount int64 `json:"sold_splitted_products_count"`
SoldProductsCount int64 `json:"sold_products_count"`
InStockProductsCount int64 `json:"in_stock_products_count"`
InStockSplittedProductsCount int64 `json:"in_stock_splitted_products_count"`
HasSplittedProducts bool `json:"has_splitted_products"`
UpdatedAt string `json:"updated_at"`
CreatedAt string `json:"created_at"`
PostPaymentURL *string `json:"post_payment_url"`
PrePaymentSettings *PrePaymentSettings `json:"pre_payment_settings"`
NotificationSettings *NotificationSettings `json:"notification_settings"`
}
Offer — карточка оффера. Её же возвращают создание и обновление.
type OfferListStatus ¶
type OfferListStatus string
OfferListStatus — фильтр списка. Archived в этот фильтр не входит.
const ( OfferListStatusActive OfferListStatus = "active" OfferListStatusPaused OfferListStatus = "paused" OfferListStatusDraft OfferListStatus = "draft" )
type OfferOption ¶ added in v1.1.0
type OfferOption struct {
ID int64 `json:"id"`
Status OfferOptionStatus `json:"status"`
Type OfferOptionType `json:"type"`
TitleRU *string `json:"title_ru"`
TitleEN *string `json:"title_en"`
CommentRU *string `json:"comment_ru"`
CommentEN *string `json:"comment_en"`
IsRequired bool `json:"is_required"`
IsPriceModifierHidden bool `json:"is_price_modifier_hidden"`
HasSplittedProducts bool `json:"has_splitted_products"`
Position int64 `json:"position"`
Variants []OfferVariant `json:"variants"`
}
OfferOption — опция оффера v2.
type OfferOptionPage ¶ added in v1.1.0
type OfferOptionPage struct {
Options []OfferOption
Pagination Pagination
}
OfferOptionPage — страница опций оффера.
type OfferOptionStatus ¶ added in v1.1.0
type OfferOptionStatus string
OfferOptionStatus — статус опции. В фильтре видимости archived нет.
const ( OfferOptionActive OfferOptionStatus = "active" OfferOptionHidden OfferOptionStatus = "hidden" OfferOptionArchived OfferOptionStatus = "archived" )
type OfferOptionType ¶ added in v1.1.0
type OfferOptionType string
OfferOptionType — тип опции оффера v2.
const ( OfferOptionText OfferOptionType = "text" OfferOptionMultilineText OfferOptionType = "multiline_text" OfferOptionCheckBox OfferOptionType = "check_box" OfferOptionRadioButton OfferOptionType = "radio_button" )
type OfferOptionWrite ¶ added in v1.1.0
type OfferOptionWrite struct {
ID *int64 `json:"id,omitempty"`
Type *OfferOptionType `json:"type,omitempty"`
Status *OfferOptionStatus `json:"status,omitempty"`
HasSplittedProducts *bool `json:"has_splitted_products,omitempty"`
TitleRU *string `json:"title_ru,omitempty"`
TitleEN *string `json:"title_en,omitempty"`
CommentRU *string `json:"comment_ru,omitempty"`
CommentEN *string `json:"comment_en,omitempty"`
IsRequired *bool `json:"is_required,omitempty"`
IsPriceModifierHidden *bool `json:"is_price_modifier_hidden,omitempty"`
Position *int64 `json:"position,omitempty"`
}
OfferOptionWrite — создание или обновление опции. Nil-поле в JSON не попадает.
type OfferPage ¶
type OfferPage struct {
Offers []OfferSummary
Pagination Pagination
}
OfferPage — одна страница списка офферов.
type OfferProduct ¶ added in v1.1.0
type OfferProduct struct {
ID int64 `json:"id"`
Value string `json:"value"`
Status OfferProductStatus `json:"status"`
CreatedAt string `json:"created_at"`
}
OfferProduct — ключ на складе оффера или варианта.
type OfferProductInput ¶ added in v1.1.0
type OfferProductInput struct {
Value string `json:"value"`
}
OfferProductInput — значение ключа при создании.
type OfferProductPage ¶ added in v1.1.0
type OfferProductPage struct {
Products []OfferProduct
Pagination Pagination
}
OfferProductPage — страница ключей.
type OfferProductStatus ¶ added in v1.1.0
type OfferProductStatus string
OfferProductStatus — статус ключа на складе оффера.
const ( OfferProductInStock OfferProductStatus = "in_stock" OfferProductSold OfferProductStatus = "sold" OfferProductArchived OfferProductStatus = "archived" )
type OfferSort ¶
type OfferSort string
OfferSort — сортировка списка офферов.
const ( OfferSortPriceAsc OfferSort = "price_asc" OfferSortPriceDesc OfferSort = "price_desc" OfferSortSalesCountAsc OfferSort = "sales_count_asc" OfferSortSalesCountDesc OfferSort = "sales_count_desc" OfferSortProductsCountAsc OfferSort = "products_count_asc" OfferSortProductsCountDesc OfferSort = "products_count_desc" )
type OfferStatus ¶
type OfferStatus string
OfferStatus — статус оффера в карточке и списке.
const ( OfferStatusDraft OfferStatus = "draft" OfferStatusActive OfferStatus = "active" OfferStatusPaused OfferStatus = "paused" OfferStatusArchived OfferStatus = "archived" )
type OfferSummary ¶
type OfferSummary struct {
ID int64 `json:"id"`
Status OfferStatus `json:"status"`
TitleRU *string `json:"title_ru"`
TitleEN *string `json:"title_en"`
DescriptionRU *string `json:"description_ru"`
DescriptionEN *string `json:"description_en"`
Price *Decimal `json:"price"`
Currency Currency `json:"currency"`
IsAutoselling *bool `json:"is_autoselling"`
Category Category `json:"category"`
MinQuantity *int64 `json:"min_quantity"`
MaxQuantity *int64 `json:"max_quantity"`
Quantity *int64 `json:"quantity"`
IsUnlimitedQuantity *bool `json:"is_unlimited_quantity"`
InstructionsRU *string `json:"instructions_ru"`
InstructionsEN *string `json:"instructions_en"`
PostPaymentURL *string `json:"post_payment_url"`
Delivery *Delivery `json:"delivery"`
CoverImageRUURL string `json:"cover_image_ru_url"`
CoverImageENURL *string `json:"cover_image_en_url"`
HasOptions bool `json:"has_options"`
HasProducts bool `json:"has_products"`
HasSplittedProducts bool `json:"has_splitted_products"`
CreatedAt string `json:"created_at"`
UpdatedAt string `json:"updated_at"`
PrePaymentSettings *PrePaymentSettings `json:"pre_payment_settings"`
NotificationSettings *NotificationSettings `json:"notification_settings"`
}
OfferSummary — элемент списка офферов.
type OfferVariant ¶ added in v1.1.0
type OfferVariant struct {
ID int64 `json:"id"`
TitleRU *string `json:"title_ru"`
TitleEN *string `json:"title_en"`
Price Decimal `json:"price"`
DiscountType DiscountType `json:"discount_type"`
ImpactType ImpactType `json:"impact_type"`
IsDefault bool `json:"is_default"`
Status OfferOptionStatus `json:"status"`
Position int64 `json:"position"`
InStock *int64 `json:"in_stock_products_count"`
Sold *int64 `json:"sold_products_count"`
}
OfferVariant — вариант опции. Остатки заполнены в GetOfferOption.
type OfferVariantWrite ¶ added in v1.1.0
type OfferVariantWrite struct {
ID *int64 `json:"id,omitempty"`
TitleRU *string `json:"title_ru,omitempty"`
TitleEN *string `json:"title_en,omitempty"`
Price *Decimal `json:"price,omitempty"`
DiscountType *DiscountType `json:"discount_type,omitempty"`
ImpactType *ImpactType `json:"impact_type,omitempty"`
IsDefault *bool `json:"is_default,omitempty"`
Status *OfferOptionStatus `json:"status,omitempty"`
Position *int64 `json:"position,omitempty"`
}
OfferVariantWrite — создание или обновление варианта. Nil-поле в JSON не попадает.
type OfferWrite ¶
type OfferWrite struct {
TitleRU *string `json:"title_ru,omitempty"`
TitleEN *string `json:"title_en,omitempty"`
DescriptionRU *string `json:"description_ru,omitempty"`
DescriptionEN *string `json:"description_en,omitempty"`
InstructionsRU *string `json:"instructions_ru,omitempty"`
InstructionsEN *string `json:"instructions_en,omitempty"`
CoverImageRU *string `json:"cover_image_ru,omitempty"`
CoverImageEN *string `json:"cover_image_en,omitempty"`
Price *Decimal `json:"price,omitempty"`
Currency *Currency `json:"currency,omitempty"`
IsAutoselling *bool `json:"is_autoselling,omitempty"`
CategoryID *int64 `json:"category_id,omitempty"`
MinQuantity *int64 `json:"min_quantity,omitempty"`
MaxQuantity *int64 `json:"max_quantity,omitempty"`
Quantity *int64 `json:"quantity,omitempty"`
IsUnlimitedQuantity *bool `json:"is_unlimited_quantity,omitempty"`
PostPaymentURL *string `json:"post_payment_url,omitempty"`
Delivery *Delivery `json:"delivery,omitempty"`
PrePaymentSettings *PrePaymentSettingsWrite `json:"pre_payment_settings,omitempty"`
NotificationSettings *NotificationSettingsWrite `json:"notification_settings,omitempty"`
}
OfferWrite — тело создания и частичного обновления оффера. Nil-поле в JSON не попадает.
type OptionArchive ¶ added in v1.1.0
type OptionArchive struct {
OptionIDs []int64 `json:"option_ids,omitempty"`
DeleteAll *DeleteAll `json:"delete_all,omitempty"`
}
OptionArchive — архив опций. Пустой набор без delete_all в сеть не уходит.
type OptionVisibility ¶ added in v1.1.0
type OptionVisibility struct {
ID int64 `json:"id"`
Status OfferOptionStatus `json:"status"`
}
OptionVisibility — видимость одной опции. Статус только active или hidden.
type Options ¶
type Options struct {
// BaseURL — база API. Пустое значение равно DefaultBaseURL.
BaseURL string
// HTTPClient — свой HTTP-клиент. Nil заменяется клиентом с таймаутом 30 секунд.
// Переданный клиент не изменяется.
HTTPClient *http.Client
// APIKey — ключ продавца. Пустое значение делает New ошибкой.
APIKey string
// SellerID — идентификатор продавца для контура v1. Ноль допустим, пока v1 не вызывается.
SellerID int64
// Locale — заголовок locale. Пустое значение равно ru.
Locale string
// MaxRetries — сколько повторных попыток получает безопасный GET после первой.
// Ноль равен двум. Отрицательное значение выключает повторы.
MaxRetries int
// RetryBackoffMin — нижняя граница паузы между повторами. Ноль равно 100 миллисекундам.
RetryBackoffMin time.Duration
// RetryBackoffMax — верхняя граница паузы между повторами. Ноль равно 2 секундам.
RetryBackoffMax time.Duration
// Clock — часы для timestamp и срока token. Nil вызывает time.Now.
Clock func() time.Time
}
Options задаёт клиент. Нулевые поля, кроме APIKey, безопасны. New не выполняет сетевых вызовов.
type Order ¶
type Order struct {
ItemID *int64 `json:"item_id"`
ContentID int64 `json:"content_id"`
CartUID *string `json:"cart_uid"`
Name *string `json:"name"`
Amount Decimal `json:"amount"`
CurrencyType string `json:"currency_type"`
InvoiceState InvoiceState `json:"invoice_state"`
PurchaseDate string `json:"purchase_date"`
DatePay *string `json:"date_pay"`
AgentID *int64 `json:"agent_id"`
AgentPercent *Decimal `json:"agent_percent"`
AgentFee Decimal `json:"agent_fee"`
QueryString *string `json:"query_string"`
UnitGoods *string `json:"unit_goods"`
CountGoods *string `json:"cnt_goods"`
PromoCode *string `json:"promo_code"`
BonusCode *string `json:"bonus_code"`
Feedback *OrderFeedback `json:"feedback"`
UniqueCodeState OrderCodeState `json:"unique_code_state"`
Options []OrderOption `json:"options"`
Buyer Buyer `json:"buyer_info"`
Owner int64 `json:"owner"`
DayLock int64 `json:"day_lock"`
LockState string `json:"lock_state"`
Profit Decimal `json:"profit"`
ExternalOrderID *string `json:"external_order_id"`
}
Order — содержание заказа из purchase/info.
type OrderCodeState ¶
type OrderCodeState struct {
State *int64 `json:"state"`
DateCheck *string `json:"date_check"`
DateDelivery *string `json:"date_delivery"`
DateConfirmed *string `json:"date_confirmed"`
DateRefuted *string `json:"date_refuted"`
}
OrderCodeState — состояние уникального кода в заказе.
type OrderFeedback ¶
type OrderFeedback struct {
Deleted bool `json:"deleted"`
Feedback string `json:"feedback"`
Type FeedbackType `json:"feedback_type"`
Comment *string `json:"comment"`
}
OrderFeedback — отзыв в карточке заказа.
type OrderOption ¶
type OrderOption struct {
ID int64 `json:"id"`
Name *string `json:"name"`
UserData string `json:"user_data"`
UserDataID *int64 `json:"user_data_id"`
}
OrderOption — опция товара в заказе.
type Pagination ¶
type Pagination struct {
Page int64 `json:"page"`
Limit int64 `json:"limit"`
HasNextPage bool `json:"has_next_page"`
HasPreviousPage bool `json:"has_previous_page"`
TotalPages int64 `json:"total_pages"`
TotalCount *int64 `json:"total_count"`
}
Pagination — страница v2, включая устаревшие total_pages и total_count.
type PayCurrency ¶ added in v1.1.0
type PayCurrency struct {
Currency *string `json:"currency"`
Code *string `json:"code"`
Price *Decimal `json:"price"`
Limit PayLimit `json:"limit"`
}
PayCurrency — валюта способа оплаты.
type PayMethod ¶ added in v1.1.0
type PayMethod struct {
Name *string `json:"name"`
Currencies []PayCurrency `json:"currencies"`
}
PayMethod — способ оплаты в карточке товара.
type PrePaymentSettings ¶
type PrePaymentSettings struct {
IsEnabled bool `json:"is_enabled"`
URL *string `json:"url"`
AllowPayment bool `json:"allow_payment"`
}
PrePaymentSettings — проверка до оплаты.
type PrePaymentSettingsWrite ¶
type PrePaymentSettingsWrite struct {
IsEnabled *bool `json:"is_enabled,omitempty"`
URL *string `json:"url,omitempty"`
AllowPayment *bool `json:"allow_payment,omitempty"`
}
PrePaymentSettingsWrite — частичные настройки проверки до оплаты.
type PriceChangeType ¶ added in v1.1.0
type PriceChangeType string
PriceChangeType — как массовая правка меняет цену варианта.
const ( PricePercentPlus PriceChangeType = "percentplus" PricePercentMinus PriceChangeType = "percentminus" PriceMinus PriceChangeType = "priceminus" PricePlus PriceChangeType = "priceplus" )
type ProductArchive ¶ added in v1.1.0
type ProductArchive struct {
ProductIDs []int64 `json:"product_ids,omitempty"`
DeleteAll *DeleteAll `json:"delete_all,omitempty"`
}
ProductArchive — архив ключей оффера или варианта.
type ProductCard ¶ added in v1.1.0
type ProductCard struct {
ID *int64 `json:"id"`
PrevID *int64 `json:"id_prev"`
NextID *int64 `json:"id_next"`
Name *string `json:"name"`
Price *Decimal `json:"price"`
Currency *string `json:"currency"`
URL *string `json:"url"`
Info *string `json:"info"`
AddInfo *string `json:"add_info"`
ReleaseDate *string `json:"release_date"`
AgencyFee *string `json:"agency_fee"`
AgencySum *string `json:"agency_sum"`
AgencyID *int64 `json:"agency_id"`
Collection *string `json:"collection"`
Property *int64 `json:"propertygood"`
Available *int64 `json:"is_available"`
ShowRest *int64 `json:"show_rest"`
InStock *int64 `json:"num_in_stock"`
InLock *int64 `json:"num_in_lock"`
Prices ProductPrices `json:"prices"`
PaymentMethods []PayMethod `json:"payment_methods"`
Unit *ProductUnit `json:"prices_unit"`
CodeVerification json.RawMessage `json:"unique_code_verification"`
Images []ProductImage `json:"preview_imgs"`
Videos []ProductImage `json:"preview_videos"`
Type *string `json:"type"`
Text *string `json:"text"`
File *string `json:"file"`
CategoryID *int64 `json:"category_id"`
Breadcrumbs []ProductCrumb `json:"breadcrumbs"`
Discounts []json.RawMessage `json:"discounts"`
Units []json.RawMessage `json:"units"`
Present json.RawMessage `json:"present"`
GiftFee *string `json:"gift_commiss"`
Options []ProductOption `json:"options"`
OptionsCheck *int64 `json:"options_check"`
Statistics ProductStats `json:"statistics"`
Seller ProductSeller `json:"seller"`
Sale SaleInfo `json:"sale_info"`
}
ProductCard — карточка товара v1.
type ProductCrumb ¶ added in v1.1.0
type ProductImage ¶ added in v1.1.0
type ProductImage struct {
URL *string `json:"url"`
Width *int64 `json:"width"`
Height *int64 `json:"height"`
}
ProductImage — превью товара.
type ProductOption ¶ added in v1.1.0
type ProductOption struct {
Name int64 `json:"name"`
Label string `json:"label"`
Type *string `json:"type"`
SeparateContent *int64 `json:"separate_content"`
Required *int64 `json:"required"`
ModifierVisible *int64 `json:"modifier_visible"`
Hidden *int64 `json:"hidden"`
Variants []ProductOptionVariant `json:"variants"`
}
ProductOption — опция карточки v1. Name в снимке integer.
type ProductOptionVariant ¶ added in v1.1.0
type ProductOptionVariant struct {
Value *int64 `json:"value"`
Text *string `json:"text"`
Default *int64 `json:"default"`
Modify *string `json:"modify"`
ModifyType *string `json:"modify_type"`
ModifyValue *string `json:"modify_value"`
ModifyDefault *string `json:"modify_value_default"`
InStock *int64 `json:"num_in_stock"`
Visible *int64 `json:"visible"`
}
ProductOptionVariant — вариант опции в карточке v1. Суммы модификатора в снимке строки.
type ProductPriceChange ¶ added in v1.1.0
type ProductPriceChange struct {
ProductID *int64 `json:"product_id,omitempty"`
Price *Decimal `json:"price,omitempty"`
Variants []VariantPriceChange `json:"variants,omitempty"`
}
ProductPriceChange — правка цены товара и его вариантов.
type ProductPrices ¶ added in v1.1.0
type ProductPrices struct {
Initial *MoneyTrio `json:"initial"`
Default *MoneyTrio `json:"default"`
}
ProductPrices — начальная и обычная цена карточки товара.
type ProductSeller ¶ added in v1.1.0
ProductSeller — продавец в карточке товара.
type ProductStats ¶ added in v1.1.0
type ProductStats struct {
Sales int64 `json:"sales"`
Refunds int64 `json:"refunds"`
GoodReviews int64 `json:"good_reviews"`
BadReviews int64 `json:"bad_reviews"`
}
ProductStats — счётчики карточки товара.
type ProductTask ¶ added in v1.1.0
type ProductTask struct {
ID string `json:"TaskId"`
Status ProductTaskStatus `json:"Status"`
SuccessCount int64 `json:"SuccessCount"`
ErrorCount int64 `json:"ErrorCount"`
TotalCount int64 `json:"TotalCount"`
Errors []ProductTaskError `json:"ErrorsDescriptions"`
}
ProductTask — статус задачи v1. Это не AsyncJob: другой путь и другие поля.
type ProductTaskError ¶ added in v1.1.0
ProductTaskError — одна ошибка массовой правки цен.
type ProductTaskStatus ¶ added in v1.1.0
type ProductTaskStatus int
ProductTaskStatus — статус задачи правки цен v1. В снимке это 1, 2 и 3.
const ( ProductTaskStatus1 ProductTaskStatus = 1 ProductTaskStatus2 ProductTaskStatus = 2 ProductTaskStatus3 ProductTaskStatus = 3 )
type ProductUnit ¶ added in v1.1.0
type ProductUnit struct {
Name *string `json:"unit_name"`
Amount *Decimal `json:"unit_amount"`
AmountTo *string `json:"unit_amount_desc"`
Currency *string `json:"unit_currency"`
Count *Decimal `json:"unit_cnt"`
Min *Decimal `json:"unit_cnt_min"`
Max *Decimal `json:"unit_cnt_max"`
CountTo *string `json:"unit_cnt_desc"`
Fixed *bool `json:"unit_fixed"`
OnlyInt *bool `json:"unit_only_int"`
}
ProductUnit — продажа единицами.
type Receipt ¶ added in v1.1.0
type Receipt struct {
AccountOperationID int64 `json:"account_operation_id"`
Operation ReceiptOperation `json:"operation"`
OwnerID int64 `json:"owner_id"`
Product ReceiptProduct `json:"product"`
CodeCheckAt *string `json:"code_check_datetime"`
FreeAt *string `json:"date_free"`
FreeDescription *string `json:"free_description"`
Response *string `json:"response"`
}
Receipt — одна операция счёта.
type ReceiptCodeFilter ¶ added in v1.1.0
type ReceiptCodeFilter string
ReceiptCodeFilter — фильтр проверки кода в чеках.
const ( ReceiptOnlyWaitingCode ReceiptCodeFilter = "only_waiting_code_check" ReceiptHideWaitingCode ReceiptCodeFilter = "hide_waiting_code_check" )
type ReceiptOperation ¶ added in v1.1.0
type ReceiptOperation struct {
ID int64 `json:"id"`
Type string `json:"type"`
DateTime string `json:"datetime"`
Percent int64 `json:"percent"`
Price Decimal `json:"price"`
Currency string `json:"currency"`
OnAccount Decimal `json:"on_account"`
}
ReceiptOperation — движение в чеке.
type ReceiptPage ¶ added in v1.1.0
type ReceiptPage struct {
Page int64
Count int64
HasNextPage bool
HasPreviousPage bool
TotalCount int64
TotalPages int64
Items []Receipt
}
ReceiptPage — страница чеков.
type ReceiptProduct ¶ added in v1.1.0
type ReceiptProduct struct {
ID int64 `json:"id"`
Name []LocalizedText `json:"name"`
Deleted bool `json:"deleted"`
}
ReceiptProduct — товар в чеке.
type ReceiptType ¶ added in v1.1.0
type ReceiptType string
ReceiptType — тип операции в чеках.
const ( ReceiptAgentAccruals ReceiptType = "agent_accurals" ReceiptProductSales ReceiptType = "product_sales" ReceiptAddFunds ReceiptType = "add_funds" ReceiptExchangeResponse ReceiptType = "exchange_response" ReceiptExchangeRequest ReceiptType = "exchange_request" ReceiptRefund ReceiptType = "refund" ReceiptAdvGoods ReceiptType = "adv_goods" ReceiptExternalCommission ReceiptType = "external_commissions" ReceiptDiskRent ReceiptType = "hard_disk_rent" ReceiptPartnerSpace ReceiptType = "extra_partner_space" ReceiptGiftCertificates ReceiptType = "gift_certificates" ReceiptWalletTransfer ReceiptType = "transfer_to_wallet" )
type Review ¶ added in v1.1.0
type Review struct {
ID int64 `json:"id"`
Info string `json:"info"`
Good int64 `json:"good"`
Type string `json:"type"`
Date string `json:"date"`
InvoiceID Decimal `json:"invoice_id"`
Name string `json:"name"`
Comment *string `json:"comment"`
OwnerID int64 `json:"owner_id"`
}
Review — отзыв v1. InvoiceID в снимке number, дата остаётся строкой.
type ReviewFilter ¶ added in v1.1.0
type ReviewFilter string
ReviewFilter — фильтр отзывов v1.
const ( ReviewGood ReviewFilter = "good" ReviewBad ReviewFilter = "bad" ReviewAll ReviewFilter = "all" )
type ReviewPage ¶ added in v1.1.0
type ReviewPage struct {
TotalPages int64
TotalItems int64
TotalGood int64
TotalBad int64
Reviews []Review
}
ReviewPage — страница отзывов.
type SaleInfo ¶ added in v1.1.0
type SaleInfo struct {
BasePrice *Decimal `json:"common_base_price"`
PriceUSD *Decimal `json:"common_price_usd"`
PriceEUR *Decimal `json:"common_price_eur"`
PriceRUR *Decimal `json:"common_price_rur"`
End *string `json:"sale_end"`
Percent *string `json:"sale_percent"`
}
SaleInfo — общая акция товара v1. Даты остаются строками.
type SellerGoods ¶ added in v1.1.0
type SellerGoods struct {
SellerID int64
SellerName string
Count int64
Pages int64
Page int64
Order string
Direction string
Products []CatalogProduct
}
SellerGoods — страница товаров продавца.
type SellerGoodsQuery ¶ added in v1.1.0
type SellerGoodsQuery struct {
SellerID *int64 `json:"id_seller,omitempty"`
Order *GoodsOrder `json:"order_col,omitempty"`
Direction *SortDirection `json:"order_dir,omitempty"`
Rows *int64 `json:"rows,omitempty"`
Page *int64 `json:"page,omitempty"`
Currency *GoodsCurrency `json:"currency,omitempty"`
Lang *Lang `json:"lang,omitempty"`
ShowHidden *int64 `json:"show_hidden,omitempty"`
OwnerID *int64 `json:"owner_id,omitempty"`
}
SellerGoodsQuery — тело POST seller-goods. Nil-поле в JSON не попадает.
type SortDirection ¶ added in v1.1.0
type SortDirection string
SortDirection — направление сортировки.
const ( SortAsc SortDirection = "asc" SortDesc SortDirection = "desc" )
type UniqueCode ¶
type UniqueCode struct {
InvoiceID int64 `json:"inv"`
GoodsID int64 `json:"id_goods"`
Amount Decimal `json:"amount"`
CurrencyType string `json:"type_curr"`
AmountUSD Decimal `json:"amount_usd"`
Profit Decimal `json:"profit"`
DatePay string `json:"date_pay"`
Email *string `json:"email"`
Name string `json:"name_invoice"`
Lang *string `json:"lang"`
AgentID *int64 `json:"agent_id"`
AgentPercent *string `json:"agent_percent"`
QueryString *string `json:"query_string"`
UnitGoods *string `json:"unit_goods"`
CountGoods *string `json:"cnt_goods"`
PromoCode *string `json:"promo_code"`
BonusCode *string `json:"bonus_code"`
CartUID *string `json:"cart_uid"`
UniqueCodeState UniqueCodeState `json:"unique_code_state"`
Options []UniqueCodeOption `json:"options"`
}
UniqueCode — результат проверки уникального кода. AgentPercent здесь строка: в этой схеме тип другой, чем у заказа.
type UniqueCodeOption ¶
type UniqueCodeOption struct {
ID *int64 `json:"id"`
Name *string `json:"name"`
Value *string `json:"value"`
VariantID *int64 `json:"variant_id"`
}
UniqueCodeOption — опция товара в ответе уникального кода.
type UniqueCodeState ¶
type UniqueCodeState struct {
State int64 `json:"state"`
DateCheck *string `json:"date_check"`
DateDelivery *string `json:"date_delivery"`
DateConfirmed *string `json:"date_confirmed"`
DateRefuted *string `json:"date_refuted"`
}
UniqueCodeState — состояние уникального кода при проверке кода.
type VariantArchive ¶ added in v1.1.0
type VariantArchive struct {
VariantIDs []int64 `json:"option_variant_ids,omitempty"`
DeleteAll *DeleteAll `json:"delete_all,omitempty"`
}
VariantArchive — архив вариантов. Ответ содержит job_id, клиент его не опрашивает.
type VariantPriceChange ¶ added in v1.1.0
type VariantPriceChange struct {
VariantID *int64 `json:"variant_id,omitempty"`
Rate *Decimal `json:"rate,omitempty"`
Type *PriceChangeType `json:"type,omitempty"`
}
VariantPriceChange — правка цены одного варианта. Nil-поле в JSON не попадает.
type VariantVisibility ¶ added in v1.1.0
type VariantVisibility struct {
ID int64 `json:"id"`
Status OfferOptionStatus `json:"status"`
}
VariantVisibility — видимость одного варианта. Статус только active или hidden.