Files
go-vchasno-kassa/api/fiscal.go
2026-01-16 02:21:37 +03:00

116 lines
2.4 KiB
Go

package api
import (
"context"
"encoding/json"
"fmt"
"io"
"log"
)
func (c *Client) executeRequest(ctx context.Context, request FiscalRequest, response interface{}) error {
request.Device = c.device
reqJson, err := json.Marshal(request)
if err != nil {
return fmt.Errorf("failed to marshal request: %w", err)
}
url := c.apiBaseURL + c.fiscalEndpoint
log.Printf("[VCHASNO] POST %s", url)
log.Printf("[VCHASNO] Request: %s", string(reqJson))
resp, err := c.resty.R().
SetContext(ctx).
SetHeader("Authorization", c.token).
SetHeader("Content-Type", "application/json").
SetBody(reqJson).
Post(url)
if err != nil {
return fmt.Errorf("request failed: %w", err)
}
body, err := io.ReadAll(resp.Body)
if err != nil {
return fmt.Errorf("failed to read response: %w", err)
}
log.Printf("[VCHASNO] Response (status %d): %s", resp.StatusCode(), string(body))
if resp.StatusCode() != 200 {
return fmt.Errorf("api error (status %d): %s", resp.StatusCode(), string(body))
}
if err := json.Unmarshal(body, response); err != nil {
return fmt.Errorf("failed to unmarshal response: %w, body: %s", err, string(body))
}
return nil
}
func (c *Client) OpenShift(ctx context.Context, cashier string) (*SellResponse, error) {
request := FiscalRequest{
Fiscal: Fiscal{
Task: TaskOpenShift,
Cashier: cashier,
},
}
var response SellResponse
if err := c.executeRequest(ctx, request, &response); err != nil {
return nil, err
}
return &response, nil
}
func (c *Client) CloseShift(ctx context.Context, cashier string) (*ZReportResponse, error) {
request := FiscalRequest{
Fiscal: Fiscal{
Task: TaskZReport,
Cashier: cashier,
},
}
var response ZReportResponse
if err := c.executeRequest(ctx, request, &response); err != nil {
return nil, err
}
return &response, nil
}
type SellParams struct {
Cashier string
Source string
Rows []ReceiptRow
Pays []ReceiptPay
Userinfo *Userinfo
CommentUP string
}
func (c *Client) Sell(ctx context.Context, params SellParams) (*SellResponse, error) {
receipt := NewReceipt(params.Rows, params.Pays, params.CommentUP)
request := FiscalRequest{
Source: params.Source,
Fiscal: Fiscal{
Task: TaskSell,
Cashier: params.Cashier,
Receipt: &receipt,
},
}
if params.Userinfo != nil {
request.Userinfo = *params.Userinfo
}
var response SellResponse
if err := c.executeRequest(ctx, request, &response); err != nil {
return nil, err
}
return &response, nil
}