checkbox

package module
v0.0.0-...-da5fc79 Latest Latest
Warning

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

Go to latest
Published: Dec 11, 2022 License: MIT Imports: 6 Imported by: 0

README

checkbox-ua-api-sdk

Golang SDK для роботи з API Checkbox.ua
(under development)

Реалізовані деякі базові функції, яких достатньо для відкриття зміни і створення фіскальних чеків. Implemented some basic functions.

Alternative: Auto generated Checkbox SDK

Usage

Приклад:

package main

import (
	"log"
	"github.com/lexesv/checkbox-ua-api-sdk"
)

func main() {
	LicenseKey := "<LicenseKey>"
	CashierLogin := "<CashierLogin>"
	CashierPassword := "<CashierPassword>"
	CashierPinCode := "<CashierPinCode>"

	ChBox := checkbox.New(LicenseKey, CashierLogin, CashierPassword, CashierPinCode)

	sign, err := ChBox.SignIn()
	if err != nil {
		log.Fatal(err)
	}

	log.Println("AccessToken:", sign.AccessToken)

	profile, err := ChBox.GetCashierProfile(sign.AccessToken)
	if err != nil {
		log.Fatal(err)
	}
	log.Printf("ID: %s; FullName: %s\n", profile.Id, profile.FullName)

	rinfo, err := ChBox.GetCashRegistersInfo()
	if err != nil {
		log.Fatal(err)
	}
	log.Println("Has open Shift:", rinfo.HasShift)

	shift, err := ChBox.CreateShift(sign.AccessToken)
	if err != nil {
		//log.Fatal(err)
		log.Println(err)
	}
	if shift.Serial > 0 {
		log.Println("Shift success created")
		time.Sleep(time.Second * 7)
	}

	req := ChBox.NewSimpleReceipt("1", "Продаж ПЗ", 10000, 1000, "CARD", 10000)
	receipt, err := ChBox.CreateReceipt(sign.AccessToken, req)
	if err != nil {
		log.Fatal(err)
	}
	if receipt.Serial > 0 {
		log.Println("Receipt success created")
	}

	time.Sleep(time.Second * 15)

	_, err = ChBox.CloseShift(sign.AccessToken, nil)
	if err != nil {
		log.Fatal(err.Error())
	} else {
		log.Println("Shift success closed")
	}
}

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type CashRegister

type CashRegister struct {
	Id           string    `json:"id"`
	FiscalNumber string    `json:"fiscal_number"`
	Active       bool      `json:"active"`
	CreatedAt    time.Time `json:"created_at"`
	UpdatedAt    time.Time `json:"updated_at"`
	Shift        Shift     `json:"shift"`
	OfflineMode  bool      `json:"offline_mode"`
	StayOffline  bool      `json:"stay_offline"`
	Branch       struct {
		Id           string `json:"id"`
		Name         string `json:"name"`
		Address      string `json:"address"`
		Organization struct {
			Id                        string    `json:"id"`
			Title                     string    `json:"title"`
			Edrpou                    string    `json:"edrpou"`
			TaxNumber                 string    `json:"tax_number"`
			CreatedAt                 time.Time `json:"created_at"`
			UpdatedAt                 time.Time `json:"updated_at"`
			SubscriptionExp           string    `json:"subscription_exp"`
			ConcordLogin              string    `json:"concord_login"`
			ConcordUid                string    `json:"concord_uid"`
			ReceiptsRatelimitCount    int       `json:"receipts_ratelimit_count"`
			ReceiptsRatelimitInterval int       `json:"receipts_ratelimit_interval"`
			CanSendSms                bool      `json:"can_send_sms"`
		} `json:"organization"`
		CreatedAt time.Time `json:"created_at"`
		UpdatedAt time.Time `json:"updated_at"`
	} `json:"branch"`
	Address string `json:"address"`
}

type CashRegisters

type CashRegisters struct {
	Meta struct {
		Limit  int `json:"limit"`
		Offset int `json:"offset"`
	} `json:"meta"`
	Results []CashRegister `json:"results"`
}

type CashRegistersInfo

type CashRegistersInfo struct {
	Id             string    `json:"id"`
	FiscalNumber   string    `json:"fiscal_number"`
	CreatedAt      time.Time `json:"created_at"`
	UpdatedAt      time.Time `json:"updated_at"`
	Address        string    `json:"address"`
	Title          string    `json:"title"`
	OfflineMode    bool      `json:"offline_mode"`
	StayOffline    bool      `json:"stay_offline"`
	HasShift       bool      `json:"has_shift"`
	DocumentsState struct {
		LastReceiptCode int `json:"last_receipt_code"`
		LastReportCode  int `json:"last_report_code"`
		LastZReportCode int `json:"last_z_report_code"`
	} `json:"documents_state"`
}

CashRegistersInfo "id" - унікальний ідентифікатор каси ПРРО у форматі UUID "fiscal_number" - фіскальний номер каси "created_at" - дата створення каси "updated_at" - дата останнього оновлення (зміни) облікових даних каси "address" - адреса розміщення каси "title" - назва "offline_mode" - офлайн режим. false означає, що каса зараз у онлайні, а true означає, що каса працює у офлайн режимі. "stay_offline" - якщо даний параметр true, то це означає, що перехід у офлайн був виконаний на стороні клієнта (шляхом відправки запиту go offline, а не завдяки автоматичному офлайн переходу, який відбувається, коли не відповідає сервер ДПС) "has_shift" - параметр показує, чи має дана каса активну відкриту зміну "documents_state" - блок даних з інформацією про останній порядковий номер чека, звіта або z-звіта "last_receipt_code" - останній порядковий номер чека "last_report_code" - останній порядковий номер звіта, який не є z-звітом "last_z_report_code" - останній порядковий номер z-звіта

type CashierProfile

type CashierProfile struct {
	Id            string `json:"id"`
	FullName      string `json:"full_name"`
	Nin           string `json:"nin"`
	KeyId         string `json:"key_id"`
	SignatureType string `json:"signature_type"`
	Permissions   struct {
		Orders bool `json:"orders"`
	} `json:"permissions"`
	CreatedAt      time.Time `json:"created_at"`
	UpdatedAt      time.Time `json:"updated_at"`
	CertificateEnd time.Time `json:"certificate_end"`
	Blocked        string    `json:"blocked"`
	Organization   struct {
		Id                        string    `json:"id"`
		Title                     string    `json:"title"`
		Edrpou                    string    `json:"edrpou"`
		TaxNumber                 string    `json:"tax_number"`
		CreatedAt                 time.Time `json:"created_at"`
		UpdatedAt                 time.Time `json:"updated_at"`
		SubscriptionExp           string    `json:"subscription_exp"`
		ConcordLogin              string    `json:"concord_login"`
		ConcordUid                string    `json:"concord_uid"`
		ReceiptsRatelimitCount    int       `json:"receipts_ratelimit_count"`
		ReceiptsRatelimitInterval int       `json:"receipts_ratelimit_interval"`
		CanSendSms                bool      `json:"can_send_sms"`
	} `json:"organization"`
}

type CashierSignature

type CashierSignature struct {
	Online               bool   `json:"online"`
	Type                 string `json:"type"`
	ShiftOpenPossibility bool   `json:"shift_open_possibility"`
}

type Checkbox

type Checkbox struct {
	Conf         Config
	SuccessCodes []int
}

func New

func New(LicenseKey, CashierLogin, CashierPassword, CashierPinCode string) *Checkbox

New

Створення нового обʼєкту Checkbox

func (*Checkbox) CloseShift

func (ch *Checkbox) CloseShift(AccessToken string, req *CloseShiftPayload) (*Shift, *Error)

CloseShift

Приклад: CloseShift(AccessToken, nil)

Якщо аргумент req = nil то всі дані по Z-звіту будуть сформовані на боці серверу

Створення Z-Звіту та закриття поточної зміни користувачем (касиром).

Стан зміни встановлюється як "CLOSING" та створюється транзакція закриття зміни (поле "closing_transaction").

Для переведення зміни в статус CLOSED необхідно щоб транзакція була підписана за допомогою КЕП та доставлена в ДПС.

Статус зміни можна відслідковувати за допомогою GET запиту по шляху /api/v1/shifts/{shift_id}, де {shift_id} - ідентифікатор зміни.

Після закриття зміни в її рамках більше не можливо буде виконувати дії. Для продовження роботи потрібно створити нову зміну.

Опціонально Z-Звіт може бути сформований на стороні клієнта та переданий в тілі цього запиту

Увага! При формуванні звіту на стороні клієнту перевірка коректності розрахунку оборотів та сум продажу не виконується!

func (*Checkbox) CreateReceipt

func (ch *Checkbox) CreateReceipt(AccessToken string, req *ReceiptPayload) (resp *Receipt, err *Error)

CreateReceipt

Створення чеку продажу/повернення, його фіскалізація та доставка клієнту по email.

func (*Checkbox) CreateShift

func (ch *Checkbox) CreateShift(AccessToken string) (*Shift, *Error)

CreateShift

Відкриття нової зміни касиром.

Для створення зміни необхідно вказати ключ ліцензії конкретного пРРО розташованого в тій же торговій точці, що знаходиться касир.

Створюється об'єкт зміни в стані "CREATED" та транзакція відкриття зміни (поле "initial_transaction").

Для переведення зміни в статус OPENED необхідно щоб транзакція була підписана за допомогою КЕП та доставлена в ДПС, це як правило триває декілька секунд.

Після створення запиту необхідно відслідковувати статус зміни доки він не змінить на OPENED або CLOSED.

Статус зміни можна відслідковувати за допомогою GET запиту по шляху /api/v1/shifts/{shift_id}, де {shift_id} - ідентифікатор зміни. Або /api/v1/cashier/shift

У разі, якщо зміна перейшла у статус CLOSED - це значить, що зміна не може бути відкрита. Деталізація причини відмови у створенні зміни знаходиться в полі initial_transaciton.

Після того як робочу зміну буде успішно відкрито можна її закрити або створювати чеки.

AccessToken: Bearer <токен авторизації>

func (*Checkbox) GetCashRegister

func (ch *Checkbox) GetCashRegister(AccessToken string, CashRegisterId string) (*CashRegister, *Error)

GetCashRegister

Отримання інформації про пРРО

func (*Checkbox) GetCashRegisters

func (ch *Checkbox) GetCashRegisters(AccessToken string, InUse int, Limit, Offset int) (*CashRegisters, *Error)

GetCashRegisters

Отримання переліку доступних пРРО

InUse - Чи відображати зайняті каси (1 - тільки зайняті, 2 - тільки вільні, 0 - всі)

func (*Checkbox) GetCashRegistersInfo

func (ch *Checkbox) GetCashRegistersInfo() (*CashRegistersInfo, *Error)

GetCashRegistersInfo

Отримання інформації про пРРО за ключем ліцензії. Необхідно для агенту РРО.

func (*Checkbox) GetCashierProfile

func (ch *Checkbox) GetCashierProfile(AccessToken string) (*CashierProfile, *Error)

GetCashierProfile

Отримання інформації про поточного користувача (касира)

func (*Checkbox) GetCashierShift

func (ch *Checkbox) GetCashierShift(AccessToken string) (*Shift, *Error)

GetCashierShift

Отримання інформації про активну зміну користувача (касира)

func (*Checkbox) GetCashierSignature

func (ch *Checkbox) GetCashierSignature(AccessToken string) (*CashierSignature, *Error)

GetCashierSignature

Check Signature

func (*Checkbox) GetShift

func (ch *Checkbox) GetShift(AccessToken, ShiftId string) (*Shift, *Error)

GetShift

Отримання інформації про зміну

func (*Checkbox) NewSimpleReceipt

func (ch *Checkbox) NewSimpleReceipt(Code, Name string, Price, Quantity int, PayType string, PayVal int) *ReceiptPayload

NewSimpleReceipt

Code: Код товару

Name: Назва товару

Price: Вартість в копійках за quantity = 1000

Quantity: Кількість (Наприклад: 1 шт = 1000, 2.25 кг = 2250)

PayType: форма оплати "CASH" "CARD" "CASHLESS"

PayVal: Оплата в копійках

func (*Checkbox) Request

func (ch *Checkbox) Request(c ReqConfig) *Error

Request

Http запит до сервера API

Error status codes:

100 - Помилка виникша при роботі функції

401 - Unauthorized (Помилка авторизації. Наприклад: Неприпустимий токен JWT)

403 - Not authenticated (Запрос без авторизації)

422 - Validation Error (У випадку, якщо ваш запит не пройде валідацію формату)

400 - Bad Request (наприклад: Зміну не відкрито / Касир вже працює з даною касою)

func (*Checkbox) SetAccessKey

func (ch *Checkbox) SetAccessKey(AccessKey string)

func (*Checkbox) SetApiUrl

func (ch *Checkbox) SetApiUrl(ApiUrl string)

func (*Checkbox) SetClientName

func (ch *Checkbox) SetClientName(ClientName string)

func (*Checkbox) SetClientVersion

func (ch *Checkbox) SetClientVersion(ClientVersion string)

func (*Checkbox) Shifts

func (ch *Checkbox) Shifts(AccessToken string, Desc bool, Limit, Offset int) (*Shifts, *Error)

Shifts

Отримання змін поточного касира

func (*Checkbox) SignIn

func (ch *Checkbox) SignIn() (*SignIn, *Error)

SignIn

Авторизація за допомогою логіна і пароля касира

func (*Checkbox) SignInPinCode

func (ch *Checkbox) SignInPinCode() (*SignIn, *Error)

SignInPinCode

Авторизація за допомогою ключа ліцензії каси та PIN кода касира

func (*Checkbox) SignOut

func (ch *Checkbox) SignOut(AccessToken string) *Error

SignOut

Завершення сесії користувача

type CloseShiftPayload

type CloseShiftPayload struct {
	SkipClientNameCheck bool `json:"skip_client_name_check"`
	Report              struct {
		Id                          string           `json:"id"`
		Serial                      int              `json:"serial"`
		Payments                    []ZReportPayment `json:"payments"`              //required
		Taxes                       []ZReportTax     `json:"taxes"`                 //required
		SellReceiptsCount           int              `json:"sell_receipts_count"`   // required
		ReturnReceiptsCount         int              `json:"return_receipts_count"` //required
		CashWithdrawalReceiptsCount int              `json:"cash_withdrawal_receipts_count"`
		LastReceiptId               string           `json:"last_receipt_id"`
		Initial                     int              `json:"initial"` //required
		Balance                     int              `json:"balance"` //required
		SalesRoundUp                int              `json:"sales_round_up"`
		SalesRoundDown              int              `json:"sales_round_down"`
		ReturnsRoundUp              int              `json:"returns_round_up"`
		ReturnsRoundDown            int              `json:"returns_round_down"`
		DiscountsSum                int              `json:"discounts_sum"`
		ExtraChargeSum              int              `json:"extra_charge_sum"`
		CreatedAt                   time.Time        `json:"created_at"`
	} `json:"report"`
	FiscalCode string    `json:"fiscal_code"`
	FiscalDate time.Time `json:"fiscal_date"`
}

type Config

type Config struct {
	ApiUrl          string
	AccessKey       string
	LicenseKey      string
	ClientName      string
	ClientVersion   string
	CashierLogin    string
	CashierPassword string
	CashierPinCode  string
}

type Error

type Error struct {
	StatusCode int           `json:"statusCode,omitempty"`
	Message    string        `json:"message,omitempty"`
	Detail     MessageDetail `json:"detail,omitempty"`
}

func (*Error) Error

func (e *Error) Error() string

type Good

type Good struct {
	Good struct {
		Code           string   `json:"code"` // required  (Код товару)
		Name           string   `json:"name"` // required
		Barcode        string   `json:"barcode,omitempty"`
		ExciseBarcode  string   `json:"excise_barcode,omitempty"`
		ExciseBarcodes []string `json:"excise_barcodes,omitempty"`
		Header         string   `json:"header,omitempty"`
		Footer         string   `json:"footer,omitempty"`
		Price          int      `json:"price,omitempty"` //required (Вартість в копійках за quantity = 1000)
		Tax            []int    `json:"tax,omitempty"`
		Uktzed         string   `json:"uktzed,omitempty"`
	} `json:"good"`
	GoodId           string            `json:"good_id,omitempty"`
	Quantity         int               `json:"quantity"` // required (Кількість (Наприклад: 1 шт = 1000, 2.25 кг = 2250))
	IsReturn         bool              `json:"is_return,omitempty"`
	IsWinningsPayout bool              `json:"is_winnings_payout,omitempty"`
	Discounts        []ReceiptDiscount `json:"discounts,omitempty"`
	Sum              int               `json:"sum,omitempty"`
	Taxes            []GoodTax         `json:"taxes,omitempty"`
}

type GoodTax

type GoodTax struct {
	Id           string    `json:"id,omitempty"`
	Code         int       `json:"code,omitempty"`
	Label        string    `json:"label,omitempty"`
	Symbol       string    `json:"symbol,omitempty"`
	Rate         int       `json:"rate,omitempty"`
	ExtraRate    int       `json:"extra_rate,omitempty"`
	Included     bool      `json:"included,omitempty"`
	CreatedAt    time.Time `json:"created_at,omitempty"`
	UpdatedAt    time.Time `json:"updated_at,omitempty"`
	NoVat        bool      `json:"no_vat,omitempty"`
	AdvancedCode string    `json:"advanced_code,omitempty"`
	Value        int       `json:"value,omitempty"`
	ExtraValue   int       `json:"extra_value,omitempty"`
}

type MessageDetail

type MessageDetail []struct {
	Loc  []interface{} `json:"loc"`
	Msg  string        `json:"msg"`
	Type string        `json:"type"`
	Ctx  struct {
		LimitValue int `json:"limit_value"`
	} `json:"ctx"`
}

MessageDetail - У випадку, якщо ваш запит не пройде валідацію формату, ви отримаєте 422 Error: Unprocessable Entity зі змістом наступного вигляду, де буде вказано приблизне розташування та опис помилки:

type Receipt

type Receipt struct {
	Id          string `json:"id"`
	Transaction struct {
		Id                   string    `json:"id"`
		Serial               int       `json:"serial"`
		RequestSignedAt      time.Time `json:"request_signed_at"`
		RequestReceivedAt    time.Time `json:"request_received_at"`
		ResponseStatus       string    `json:"response_status"`
		ResponseErrorMessage string    `json:"response_error_message"`
		ResponseId           string    `json:"response_id"`
		OfflineId            string    `json:"offline_id"`
		CreatedAt            time.Time `json:"created_at"`
		UpdatedAt            time.Time `json:"updated_at"`
		PreviousHash         string    `json:"previous_hash"`
	} `json:"transaction"`
	Serial       int               `json:"serial"`
	Goods        []Good            `json:"goods"`
	Payments     []ReceiptPayment  `json:"payments"`
	TotalSum     int               `json:"total_sum"`
	TotalPayment int               `json:"total_payment"`
	TotalRest    int               `json:"total_rest"`
	RoundSum     int               `json:"round_sum"`
	FiscalCode   string            `json:"fiscal_code"`
	FiscalDate   time.Time         `json:"fiscal_date"`
	DeliveredAt  time.Time         `json:"delivered_at"`
	CreatedAt    time.Time         `json:"created_at"`
	UpdatedAt    time.Time         `json:"updated_at"`
	Taxes        []GoodTax         `json:"taxes"`
	Discounts    []ReceiptDiscount `json:"discounts"`
	OrderId      string            `json:"order_id"`
	Header       string            `json:"header"`
	Footer       string            `json:"footer"`
	Barcode      string            `json:"barcode"`
	Custom       struct {
		HtmlGlobalHeader    string `json:"html_global_header"`
		HtmlGlobalFooter    string `json:"html_global_footer"`
		HtmlBodyStyle       string `json:"html_body_style"`
		HtmlReceiptStyle    string `json:"html_receipt_style"`
		HtmlRulerStyle      string `json:"html_ruler_style"`
		HtmlLightBlockStyle string `json:"html_light_block_style"`
		TextGlobalHeader    string `json:"text_global_header"`
		TextGlobalFooter    string `json:"text_global_footer"`
	} `json:"custom"`
	IsCreatedOffline bool      `json:"is_created_offline"`
	IsSentDps        bool      `json:"is_sent_dps"`
	SentDpsAt        time.Time `json:"sent_dps_at"`
	TaxUrl           string    `json:"tax_url"`
	RelatedReceiptId string    `json:"related_receipt_id"`
	TechnicalReturn  bool      `json:"technical_return"`
	CurrencyExchange struct {
		Sell struct {
			Currency string `json:"currency"`
			Value    int    `json:"value"`
			Rate     struct {
				Code       string    `json:"code"`
				SymbolCode string    `json:"symbol_code"`
				Name       string    `json:"name"`
				Sell       int       `json:"sell"`
				Buy        int       `json:"buy"`
				Regulator  int       `json:"regulator"`
				CreatedAt  time.Time `json:"created_at"`
				UpdatedAt  time.Time `json:"updated_at"`
				Active     bool      `json:"active"`
				SellSum    int       `json:"sell_sum"`
				BuySum     int       `json:"buy_sum"`
			} `json:"rate"`
		} `json:"sell"`
		Buy struct {
			Currency string `json:"currency"`
			Value    int    `json:"value"`
			Rate     struct {
				Code       string    `json:"code"`
				SymbolCode string    `json:"symbol_code"`
				Name       string    `json:"name"`
				Sell       int       `json:"sell"`
				Buy        int       `json:"buy"`
				Regulator  int       `json:"regulator"`
				CreatedAt  time.Time `json:"created_at"`
				UpdatedAt  time.Time `json:"updated_at"`
				Active     bool      `json:"active"`
				SellSum    int       `json:"sell_sum"`
				BuySum     int       `json:"buy_sum"`
			} `json:"rate"`
		} `json:"buy"`
		Type       string `json:"type"`
		Reversal   bool   `json:"reversal"`
		ClientInfo string `json:"client_info"`
		Commission int    `json:"commission"`
		Cross      int    `json:"cross"`
	} `json:"currency_exchange"`
	Shift         Shift  `json:"shift"`
	ControlNumber string `json:"control_number"`
}

type ReceiptDiscount

type ReceiptDiscount struct {
	Type     string `json:"type,omitempty"`
	Mode     string `json:"mode,omitempty"`
	Value    int    `json:"value,omitempty"`
	TaxCode  int    `json:"tax_code,omitempty"`
	TaxCodes []int  `json:"tax_codes,omitempty"`
	Name     string `json:"name,omitempty"`
	Sum      int    `json:"sum,omitempty"`
}

type ReceiptPayload

type ReceiptPayload struct {
	Id          string `json:"id,omitempty"`
	CashierName string `json:"cashier_name,omitempty"`
	Departament string `json:"departament,omitempty"`
	Goods       []Good `json:"goods"` // required
	Delivery    struct {
		Email  string   `json:"email,omitempty"`
		Emails []string `json:"emails,omitempty"`
		Phone  string   `json:"phone,omitempty"`
	} `json:"delivery,omitempty"`
	Discounts         []ReceiptDiscount `json:"discounts,omitempty"`
	Payments          []ReceiptPayment  `json:"payments,omitempty"`
	Rounding          bool              `json:"rounding,omitempty"`
	Header            string            `json:"header,omitempty"`
	Footer            string            `json:"footer,omitempty"`
	Barcode           string            `json:"barcode,omitempty"`
	OrderId           string            `json:"order_id,omitempty"`
	RelatedReceiptId  string            `json:"related_receipt_id,omitempty"`
	PreviousReceiptId string            `json:"previous_receipt_id,omitempty"`
	TechnicalReturn   bool              `json:"technical_return,omitempty"`
	Context           struct {
		AdditionalProp1 string `json:"additionalProp1,omitempty"`
		AdditionalProp2 string `json:"additionalProp2,omitempty"`
		AdditionalProp3 string `json:"additionalProp3,omitempty"`
	} `json:"context,omitempty"`
	IsPawnshop bool `json:"is_pawnshop,omitempty"`
	Custom     struct {
		HtmlGlobalHeader    string `json:"html_global_header,omitempty"`
		HtmlGlobalFooter    string `json:"html_global_footer,omitempty"`
		HtmlBodyStyle       string `json:"html_body_style,omitempty"`
		HtmlReceiptStyle    string `json:"html_receipt_style,omitempty"`
		HtmlRulerStyle      string `json:"html_ruler_style,omitempty"`
		HtmlLightBlockStyle string `json:"html_light_block_style,omitempty"`
		TextGlobalHeader    string `json:"text_global_header,omitempty"`
		TextGlobalFooter    string `json:"text_global_footer,omitempty"`
	} `json:"custom,omitempty"`
}

type ReceiptPayment

type ReceiptPayment struct {
	Type              string `json:"type"` // "CASH" "CARD" "CASHLESS"
	PawnshopIsReturn  bool   `json:"pawnshop_is_return,omitempty"`
	Value             int    `json:"value"` // required
	Label             string `json:"label,omitempty"`
	Code              int    `json:"code,omitempty"`
	Commission        int    `json:"commission,omitempty"`
	CardMask          string `json:"card_mask,omitempty"`
	BankName          string `json:"bank_name,omitempty"`
	AuthCode          string `json:"auth_code,omitempty"`
	Rrn               string `json:"rrn,omitempty"`
	PaymentSystem     string `json:"payment_system,omitempty"`
	OwnerName         string `json:"owner_name,omitempty"`
	Terminal          string `json:"terminal,omitempty"`
	Acquiring         string `json:"acquiring,omitempty"`
	AcquirerAndSeller string `json:"acquirer_and_seller,omitempty"`
	ReceiptNo         string `json:"receipt_no,omitempty"`
	SignatureRequired bool   `json:"signature_required,omitempty"`
}

type ReqConfig

type ReqConfig struct {
	Method         string // (GET, POST, DELETE, PUT, etc)
	NeedLicenseKey bool
	Endpoint       string // example: "/api/v1/shifts"
	AccessToken    string // Bearer <токен авторизації>
	Request        interface{}
	Response       interface{}
}

type Shift

type Shift struct {
	Id      string `json:"id"`
	Serial  int    `json:"serial"`
	Status  string `json:"status,omitempty"`
	ZReport struct {
		Id        string `json:"id"`
		Serial    int    `json:"serial"`
		IsZReport bool   `json:"is_z_report"`
		Payments  []struct {
			Id                       string `json:"id"`
			Code                     int    `json:"code"`
			Type                     string `json:"type"`
			Label                    string `json:"label"`
			SellSum                  int    `json:"sell_sum"`
			ReturnSum                int    `json:"return_sum"`
			ServiceIn                int    `json:"service_in"`
			ServiceOut               int    `json:"service_out"`
			CashWithdrawal           int    `json:"cash_withdrawal"`
			CashWithdrawalCommission int    `json:"cash_withdrawal_commission"`
		} `json:"payments"`
		Taxes []struct {
			Id              string    `json:"id"`
			Code            int       `json:"code"`
			Label           string    `json:"label"`
			Symbol          string    `json:"symbol"`
			Rate            float64   `json:"rate"`
			SellSum         float64   `json:"sell_sum"`
			ReturnSum       float64   `json:"return_sum"`
			SalesTurnover   float64   `json:"sales_turnover"`
			ReturnsTurnover float64   `json:"returns_turnover"`
			NoVat           bool      `json:"no_vat"`
			AdvancedCode    string    `json:"advanced_code"`
			CreatedAt       time.Time `json:"created_at"`
			SetupDate       time.Time `json:"setup_date"`
		} `json:"taxes"`
		SellReceiptsCount           int       `json:"sell_receipts_count"`
		ReturnReceiptsCount         int       `json:"return_receipts_count"`
		CashWithdrawalReceiptsCount int       `json:"cash_withdrawal_receipts_count"`
		TransfersCount              int       `json:"transfers_count"`
		TransfersSum                int       `json:"transfers_sum"`
		Balance                     int       `json:"balance"`
		Initial                     int       `json:"initial"`
		CreatedAt                   time.Time `json:"created_at"`
		UpdatedAt                   time.Time `json:"updated_at"`
		DiscountsSum                int       `json:"discounts_sum"`
		ExtraChargeSum              int       `json:"extra_charge_sum"`
	} `json:"z_report"`
	OpenedAt           time.Time `json:"opened_at"`
	ClosedAt           time.Time `json:"closed_at"`
	InitialTransaction struct {
		Id                   string    `json:"id"`
		Type                 string    `json:"type,omitempty"`
		Serial               int       `json:"serial"`
		Status               string    `json:"status,omitempty"`
		RequestSignedAt      time.Time `json:"request_signed_at"`
		RequestReceivedAt    time.Time `json:"request_received_at"`
		ResponseStatus       string    `json:"response_status"`
		ResponseErrorMessage string    `json:"response_error_message"`
		ResponseId           string    `json:"response_id"`
		OfflineId            string    `json:"offline_id"`
		CreatedAt            time.Time `json:"created_at"`
		UpdatedAt            time.Time `json:"updated_at"`
		PreviousHash         string    `json:"previous_hash"`
	} `json:"initial_transaction"`
	ClosingTransaction struct {
		Id                   string    `json:"id"`
		Type                 string    `json:"type,omitempty"`
		Serial               int       `json:"serial"`
		Status               string    `json:"status,omitempty"`
		RequestSignedAt      time.Time `json:"request_signed_at"`
		RequestReceivedAt    time.Time `json:"request_received_at"`
		ResponseStatus       string    `json:"response_status"`
		ResponseErrorMessage string    `json:"response_error_message"`
		ResponseId           string    `json:"response_id"`
		OfflineId            string    `json:"offline_id"`
		CreatedAt            time.Time `json:"created_at"`
		UpdatedAt            time.Time `json:"updated_at"`
		PreviousHash         string    `json:"previous_hash"`
	} `json:"closing_transaction"`
	CreatedAt time.Time `json:"created_at"`
	UpdatedAt time.Time `json:"updated_at"`
	Balance   struct {
		Initial        int       `json:"initial"`
		Balance        int       `json:"balance"`
		CashSales      int       `json:"cash_sales"`
		CardSales      int       `json:"card_sales"`
		DiscountsSum   int       `json:"discounts_sum"`
		ExtraChargeSum int       `json:"extra_charge_sum"`
		CashReturns    int       `json:"cash_returns"`
		CardReturns    int       `json:"card_returns"`
		ServiceIn      int       `json:"service_in"`
		ServiceOut     int       `json:"service_out"`
		UpdatedAt      time.Time `json:"updated_at"`
	} `json:"balance"`
	Taxes []struct {
		Id              string    `json:"id"`
		Code            int       `json:"code"`
		Label           string    `json:"label"`
		Symbol          string    `json:"symbol"`
		Rate            int       `json:"rate"`
		ExtraRate       int       `json:"extra_rate"`
		Included        bool      `json:"included"`
		CreatedAt       time.Time `json:"created_at"`
		UpdatedAt       time.Time `json:"updated_at"`
		NoVat           bool      `json:"no_vat"`
		AdvancedCode    string    `json:"advanced_code"`
		Sales           int       `json:"sales"`
		Returns         int       `json:"returns"`
		SalesTurnover   int       `json:"sales_turnover"`
		ReturnsTurnover int       `json:"returns_turnover"`
	} `json:"taxes"`
	EmergencyClose        bool   `json:"emergency_close,omitempty"`
	EmergencyCloseDetails string `json:"emergency_close_details,omitempty"`
	CashRegister          struct {
		Id           string    `json:"id"`
		FiscalNumber string    `json:"fiscal_number"`
		Active       bool      `json:"active"`
		CreatedAt    time.Time `json:"created_at"`
		UpdatedAt    time.Time `json:"updated_at"`
	} `json:"cash_register,omitempty"`
	Cashier struct {
		Id          string `json:"id"`
		FullName    string `json:"full_name"`
		Nin         string `json:"nin"`
		KeyId       string `json:"key_id"`
		Permissions struct {
			Orders bool `json:"orders"`
		} `json:"permissions"`
		CreatedAt      time.Time `json:"created_at"`
		UpdatedAt      time.Time `json:"updated_at"`
		CertificateEnd time.Time `json:"certificate_end"`
		Blocked        string    `json:"blocked"`
	} `json:"cashier,omitempty"`
}

Shift "id" - унікальний ідентифікатор зміни у форматі UUID "serial" - порядковий номер зміни "status" - статус зміни. Може мати значення CREATED/OPENED/CLOSING/CLOSED (СТВОРЕНА/ВІДКРИТА/ЗАКРИВАЄТЬСЯ/ЗАКРИТА) "z_report" - блок з інформацією по z-звіту касової зміни. Для відкритої зміни це значення завжди буде null "opened_at" - мітка часу відкриття зміни у форматі ISO 8601 за шаблоном YYYY-MM-DDThh:mm:ss.ssssss±hh:mm "closed_at" - мітка часу закриття зміни у форматі ISO 8601 за шаблоном YYYY-MM-DDThh:mm:ss.ssssss±hh:mm. Для відкритої зміни завжди буде null "initial_transaction" - блок з інформацією про першу транзакцію обраної зміни "id" - унікальний ідентифікатор транзакції у форматі UUID "type" - тип транзакції. Для першої транзакції зміни це значення завжди буде SHIFT_OPEN "serial" - порядковий номер транзакції "status" - статус транзакції. Може приймати значення CREATED/PENDING/SIGNED/DELIVERED/DONE(або ERROR) (СТВОРЕНА/НА ПІДПИСАННІ/ПІДПИСАНА/ВІДПРАВЛЕНА/ВИКОНАНА(або ПОМИЛКА)) "request_signed_at" - мітка часу підписання запиту на відкриття зміни у форматі ISO 8601 за шаблоном YYYY-MM-DDThh:mm:ss.ssssss±hh:mm "request_received_at" - мітка часу отримання запиту на відкриття зміни сервером ДПС у форматі ISO 8601 за шаблоном YYYY-MM-DDThh:mm:ss.ssssss±hh:mm. Якщо запит ще не був доставлений у податкову, то дане значення буде null "response_status" - статус, отриманний від сервера ДПС у відповідь на запит. Успішний запит матиме статус OK "response_error_message" - текстовий опис помилки, при отриманні її від сервера ДПС у відповідь на запит. "response_id" - фіскальний номер транзакції відкриття зміни, отриманий від ДПС (null якщо зміна в ДПС ще не відкрилась) "offline_id" - фіскальний номер транзакції відкриття зміни у випадку, якщо вона відкрита у офлайн режимі (null якщо зміна ще не відкрита або якщо відкрита у онлайн режимі) "created_at" - мітка часу створення транзакції у у форматі ISO 8601 за шаблоном YYYY-MM-DDThh:mm:ss.ssssss±hh:mm "updated_at" - мітка часу останнього оновлення даних про транзакцію у форматі ISO 8601 за шаблоном YYYY-MM-DDThh:mm:ss.ssssss±hh:mm "previous_hash" - хеш XML даних попередньої транзакції "closing_transaction" - блок даних про останню транзакцію у зміні. Для відкритої зміни прийматиме значення null. Якщо зміна закрита, то даний блок міститиме набір даних стосовно останньої транзакції у зміні аналогічний до "initial_transaction" "created_at" - мітка часу створення зміни у форматі ISO 8601 за шаблоном YYYY-MM-DDThh:mm:ss.ssssss±hh:mm "updated_at" - мітка часу останнього оновлення даних зміни у форматі ISO 8601 за шаблоном YYYY-MM-DDThh:mm:ss.ssssss±hh:mm (null якщо дані ще ні разу не оновлювались) "balance" - блок даних по грошовому балансу обраної зміни. Всі значення передаються у копійках. "initial" - початковий баланс готівкових коштів "balance" - поточний баланс готівкових коштів "cash_sales" - сума готівкових продажів "card_sales" - сума безготівкових продажів "cash_returns" - сума готівкових повернень "card_returns" - сума безготівкових повернень "service_in" - сума службових внесень готівкових "service_out" - сума службових вилучень готівкових коштів "updated_at" - мітка часу останнього оновлення даних балансу зміни у форматі ISO 8601 за шаблоном YYYY-MM-DDThh:mm:ss.ssssss±hh:mm (null якщо дані ще ні разу не оновлювались) "taxes" - блок даних з інформацією про податкові ставки, які діють у рамках обраної зміни. Для кожної податкової ставки набір даних складається з наступних пунктів: "id" - унікальний ідентифікатор податкової ставки у форматі UUID "code" - цифровий код податкової ставки "label" - назва податкової ставки "symbol" - літерний код податкової ставки "rate" - розмір податкової ставки у відсотках "extra_rate" - розмір додаткового збору у відсотках "included" - тип податку вкладений/накладений (true/false). При використанні вкладеного податку сума податку міститься (вкладена) у загальну суму товару. Накладений податок - сума товару не містить податку, податок рахується окремо. Накладений податок використовується вкрай рідко на практиці, тому через веб-інтерфейс сайту Checkbox заблокована можливість створення податкових ставок накладеного податку. "created_at" - мітка часу створення податкової ставки у форматі ISO 8601 за шаблоном YYYY-MM-DDThh:mm:ss.ssssss±hh:mm "updated_at" - мітка часу останньої зміни параметрів податкової ставки у форматі ISO 8601 за шаблоном YYYY-MM-DDThh:mm:ss.ssssss±hh:mm. На даний момент при використанны методу /api/v1/cashier/shift, значення "updated_at" завжди повертає null "sales" - сума податку усіх чеків продажу у копійках "returns" - сума податку усіх чеків повернення у копійках "sales_turnover" - сума продажів з цією податковою ставкою (оборот) у копійках "returns_turnover" - сума повернень з цією податковою ставкою (оборот) у копійках "cash_register" - блок даних з інформацією про касу, на якій у даний момент відкрита зміна обраним касиром "id": - унікальний ідентифікатор каси у форматі UUID "fiscal_number" - фіскальний номер каси "active" - статус каси АКТИВНА/НЕАКТИВНА (true/false) "created_at" - дата реєстрації каси у форматі ISO 8601 за шаблоном YYYY-MM-DDThh:mm:ss.ssssss±hh:mm "updated_at" - дата останньої зміни даних обраної каси у форматі ISO 8601 за шаблоном YYYY-MM-DDThh:mm:ss.ssssss±hh:mm "cashier" - блок даних з інформацією про касира, яким було відкрито зміну "id" - ідентифікатор касира у форматі UUID "full_name" - ім'я касира "nin" - індивідуальний податковий номер "key_id" - ідентифікатор ключа касира, отриманий з його сертифікату "signature_type" - тип підпису касира. AGENT - якщо використовується програма Чекбокс підпис або підписання відбувається через плагін у браузері, TEST - тестовий касир, CLOUD_SIGNATURE_3 - підпис на захищеному хмарному сервісі Чекбокс, DEPOSITSIGN - хмарний підпис сервісу Депозитсайн. "permissions" - блок з інформацією про додаткові дозволи для обраного касира. Наприклад, якщо касиру дозволено доступ до API замовлень, то в даному блоці з'явиться ("orders": true) "created_at" - дата реєстрації касира у форматі ISO 8601 за шаблоном YYYY-MM-DDThh:mm:ss.ssssss±hh:mm "updated_at" - дата останньої зміни даних обраного касира у форматі ISO 8601 за шаблоном YYYY-MM-DDThh:mm:ss.ssssss±hh:mm "certificate_end" - дата завершення строку дії ЕЦП касира у форматі ISO 8601 за шаблоном YYYY-MM-DDThh:mm:ss.ssssss±hh:mm "blocked" - інформація про стан блокування касира. У випадку, якщо транзакційний процесінг отримає помилку при підписанні транзакції, пов'язану із блокуванням ЕЦП касира, в даному полі буде записано цю помилку.

type Shifts

type Shifts struct {
	Meta struct {
		Limit  int `json:"limit"`
		Offset int `json:"offset"`
	} `json:"meta"`
	Results []Shift `json:"results"`
}

type SignIn

type SignIn struct {
	Type        string `json:"type"`
	TokenType   string `json:"token_type"`
	AccessToken string `json:"access_token"`
}

type SingInPayload

type SingInPayload struct {
	Login    string `json:"login,omitempty"`
	Password string `json:"password,omitempty"`
	PinCode  string `json:"pin_code,omitempty"`
}

type ZReportPayment

type ZReportPayment struct {
	Type                     string `json:"type"` //required
	Code                     int    `json:"code"`
	Label                    string `json:"label"`       //required
	SellSum                  int    `json:"sell_sum"`    //required
	ReturnSum                int    `json:"return_sum"`  //required
	ServiceIn                int    `json:"service_in"`  //required
	ServiceOut               int    `json:"service_out"` //required
	CashWithdrawal           int    `json:"cash_withdrawal"`
	CashWithdrawalCommission int    `json:"cash_withdrawal_commission"`
}

type ZReportTax

type ZReportTax struct {
	Code            int       `json:"code"`             //required
	Label           string    `json:"label"`            //required
	Symbol          string    `json:"symbol"`           //required
	Rate            float64   `json:"rate"`             //required
	ExtraRate       float64   `json:"extra_rate"`       //required
	SellSum         float64   `json:"sell_sum"`         //required
	ReturnSum       float64   `json:"return_sum"`       //required
	SalesTurnover   float64   `json:"sales_turnover"`   //required
	ReturnsTurnover float64   `json:"returns_turnover"` //required
	SetupDate       time.Time `json:"setup_date"`       //required
	Included        bool      `json:"included"`
	NoVat           bool      `json:"no_vat"`
	AdvancedCode    string    `json:"advanced_code"`
}

Jump to

Keyboard shortcuts

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