feat(m2m): сквозной поток с веб-интерфейсами — lk-gateway BFF + admin UI + lk-emulator + mock NSD
Реализован M2-шаг-1: первый рабочий сквозной поток M2M-заявки от ЛК
через нашу систему и обратно, с двумя видимыми веб-интерфейсами.
internal/nsdadapter/mock/:
- mock NSDSender с реалистичным синтетическим Response и асинхронной
эмиссией Decision через настраиваемую задержку (Confirm/Reject/Timeout)
- использует собственный жизненный цикл, чтобы HTTP-контексты вызывающего
не прерывали эмиссию Decision до истечения DecisionDelay
internal/lkgateway/:
- REST по контракту ESIA Finance V1 (POST/GET/PATCH/list claims)
- admin web UI (/admin/, /admin/claims, /admin/claims/{id}, /admin/status):
- дашборд со статусом подсистем (postgres, crypto-service UDS,
nsd-adapter, lk-emulator callback) и счётчиками сделок
- журнал и карточка заявки с историей FSM, ответом НРД, решением
принимающей стороны и последним callback'ом
- in-memory SeedStore с 5 тестовыми клиентами и счетами депо
- фоновый consumeDecisions: подписан на mock.Sender.Decisions(),
применяет ApplyDecision и отправляет PATCH callback в ЛК
internal/lkemulator/:
- имитация ЛК клиента (порт 8083)
- веб-формы: журнал, форма «новая заявка», карточка заявки
- HTTP-клиент к lk-gateway (создание заявки + регистрация callback URL)
- приёмник PATCH callback'ов, локальное хранилище заявок,
автообновление страницы каждые 3 сек
cmd/lk-gateway/main.go и cmd/lk-emulator/main.go — заглушки заменены
на полные сервисы с graceful shutdown.
Сквозной поток проверен smoke-test'ом: подача заявки через форму
эмулятора → создание сделки в lk-gateway → Send в mock NSD →
эмиссия Decision через 3 сек → ApplyDecision → PATCH callback в ЛК →
эмулятор показывает confirmed. Дашборд lk-gateway: Total=1, Подтверждено=1.
make ci зелёный.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,70 @@
|
||||
# internal/lkgateway — BFF слой ЛК + admin web UI
|
||||
|
||||
Реализует REST-контракт ESIA Finance V1
|
||||
(`docs/lk-contract/v1/openapi.yaml`) на стороне Bridge-and-Join-s и
|
||||
admin-веб для оператора.
|
||||
|
||||
## REST API
|
||||
|
||||
- `POST /api/v1/back_office/claims/` — приём заявки от ЛК.
|
||||
Валидирует, собирает `M2MTransferRequest` через
|
||||
`m2mcore.EnrichRequest`, создаёт `m2mcore.Deal`, отправляет в НРД
|
||||
через `m2mcore.NSDSender` (на M2 — mock).
|
||||
- `GET /api/v1/back_office/claims/{id}` — карточка заявки.
|
||||
- `GET /api/v1/back_office/claims` — список с фильтрами
|
||||
(status/investor_id/created_from/created_to/limit/offset).
|
||||
- `PATCH /api/v1/back_office/claims/{id}` — placeholder для callback
|
||||
от внешней системы.
|
||||
- `/healthz` — health.
|
||||
|
||||
## Admin web UI
|
||||
|
||||
- `/admin/` — дашборд: статус системы, счётчики (Total/Confirmed/
|
||||
InProgress/Failed), последние 10 заявок.
|
||||
- `/admin/claims` — журнал всех заявок.
|
||||
- `/admin/claims/{id}` — детальная карточка: история FSM, ответ НРД
|
||||
(`M2MTransferResponse`), решение принимающей стороны
|
||||
(`M2MTransferDecision`), последний callback.
|
||||
- `/admin/status` — детальные проверки: postgres, crypto-service (UDS),
|
||||
nsd-adapter (REST), lk-emulator callback URL.
|
||||
|
||||
## Состав пакета
|
||||
|
||||
- `server.go` — `Server` обвязка: HTTP mux + сервис + фоновый
|
||||
consumeDecisions (читает из `mock.Sender.Decisions()` и обновляет
|
||||
сделки + шлёт callback в ЛК).
|
||||
- `service.go` — бизнес-логика: DTO ↔ доменные сущности m2mcore,
|
||||
оркестрация FSM, отправка callback'ов.
|
||||
- `api.go` — REST endpoints.
|
||||
- `admin.go` — HTML endpoints с шаблонами в `web/templates/`.
|
||||
- `checks.go` — проверки готовности подсистем (postgres, crypto-service,
|
||||
nsd-adapter, callback URL).
|
||||
- `seedstore.go` — in-memory `m2mcore.FansyStore` с 5 тестовыми
|
||||
клиентами и счетами депо (соответствует
|
||||
`docs/fansy-contract/v1/examples/seed-data.sql`).
|
||||
- `types.go` — DTO под OpenAPI.
|
||||
- `http_util.go` — JSON-хелперы.
|
||||
|
||||
## Конфигурация (cmd/lk-gateway/main.go, ENV)
|
||||
|
||||
| Переменная | По умолчанию | Назначение |
|
||||
|---|---|---|
|
||||
| `BJ_HTTP_ADDR` | `:8080` | Адрес HTTP |
|
||||
| `BJ_M2M_SENDER` | `MC0079200000` | DeponentCode отправителя в M2M Header |
|
||||
| `BJ_M2M_RECEIVER` | `MC0010300000` | DeponentCode получателя |
|
||||
| `BJ_DSN` | — | PostgreSQL DSN (M2-шаг-3, пока пусто = in-memory) |
|
||||
| `BJ_CRYPTO_SOCKET` | `/run/bj/crypto.sock` | UDS для crypto-service |
|
||||
| `BJ_NSD_ADAPTER_URL` | — | URL nsd-adapter HTTP (пусто = mock) |
|
||||
| `BJ_LK_CALLBACK_URL` | — | URL ЛК для PATCH callback'ов (пусто = эмулятор регистрирует свой) |
|
||||
| `BJ_NSD_PROFILE` | `demo (mock NSD)` | Имя профиля (отображается в admin) |
|
||||
| `BJ_CRYPTO_PROVIDER` | `stub` | Провайдер криптографии в admin-статусе |
|
||||
|
||||
## Что подключается в следующих шагах
|
||||
|
||||
- **M2-шаг-3**: pgx-репозиторий → миграция
|
||||
`migrations/m2m-core/001__deals.sql` уже готова.
|
||||
- **M3**: реальный `nsd-adapter` вместо mock — выставить
|
||||
`BJ_NSD_ADAPTER_URL` и реализовать в nsd-adapter поллер,
|
||||
отправляющий Decision не через канал mock, а через шину.
|
||||
- **M4**: `admin-ui` v2 на React + раздел «Сертификаты КриптоПро»
|
||||
для обновления публичных сертификатов через UI.
|
||||
@@ -0,0 +1,183 @@
|
||||
package lkgateway
|
||||
|
||||
import (
|
||||
"embed"
|
||||
"fmt"
|
||||
"html/template"
|
||||
"net/http"
|
||||
"path"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"git.zetit.ru/zuevav/Bridge-and-Join-s/internal/m2mcore"
|
||||
)
|
||||
|
||||
//go:embed web/templates/*.html
|
||||
var templatesFS embed.FS
|
||||
|
||||
// admin содержит по одному *template.Template на каждый view (layout +
|
||||
// конкретный content-шаблон). Так html/template не путается с несколькими
|
||||
// {{define "content"}} в разных файлах.
|
||||
type admin struct {
|
||||
home, claims, claim, status *template.Template
|
||||
}
|
||||
|
||||
func newAdmin() (*admin, error) {
|
||||
parse := func(content string) (*template.Template, error) {
|
||||
return template.ParseFS(templatesFS,
|
||||
"web/templates/layout.html",
|
||||
"web/templates/"+content)
|
||||
}
|
||||
home, err := parse("admin_home.html")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("parse admin_home: %w", err)
|
||||
}
|
||||
claims, err := parse("admin_claims.html")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("parse admin_claims: %w", err)
|
||||
}
|
||||
claim, err := parse("admin_claim.html")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("parse admin_claim: %w", err)
|
||||
}
|
||||
status, err := parse("admin_status.html")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("parse admin_status: %w", err)
|
||||
}
|
||||
return &admin{home: home, claims: claims, claim: claim, status: status}, nil
|
||||
}
|
||||
|
||||
// page — общий "конверт" данных для всех шаблонов.
|
||||
type page struct {
|
||||
Title string
|
||||
Active string
|
||||
Now string
|
||||
}
|
||||
|
||||
// homeData — данные дашборда.
|
||||
type homeData struct {
|
||||
page
|
||||
Status SystemStatus
|
||||
Counts struct {
|
||||
Total int
|
||||
Confirmed int
|
||||
InProgress int
|
||||
Failed int
|
||||
}
|
||||
Recent []ClaimView
|
||||
}
|
||||
|
||||
// claimsData — данные журнала.
|
||||
type claimsData struct {
|
||||
page
|
||||
Items []ClaimView
|
||||
}
|
||||
|
||||
// claimData — данные карточки.
|
||||
type claimData struct {
|
||||
page
|
||||
Claim ClaimView
|
||||
}
|
||||
|
||||
// statusData — данные страницы статуса.
|
||||
type statusData struct {
|
||||
page
|
||||
Checks []Status
|
||||
CheckedAt time.Time
|
||||
}
|
||||
|
||||
// RegisterAdmin вешает HTML-маршруты /admin/* на mux.
|
||||
func RegisterAdmin(mux *http.ServeMux, svc *Service, getOpts func() CheckOptions) error {
|
||||
a, err := newAdmin()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
mux.HandleFunc("/admin/", func(w http.ResponseWriter, r *http.Request) {
|
||||
p := strings.TrimPrefix(r.URL.Path, "/admin/")
|
||||
switch {
|
||||
case p == "" || p == "index" || p == "home":
|
||||
a.renderHome(w, r, svc, getOpts())
|
||||
case p == "claims":
|
||||
a.renderClaims(w, r, svc)
|
||||
case strings.HasPrefix(p, "claims/"):
|
||||
id := strings.TrimPrefix(p, "claims/")
|
||||
a.renderClaim(w, r, svc, id)
|
||||
case p == "status":
|
||||
a.renderStatus(w, r, getOpts())
|
||||
default:
|
||||
http.NotFound(w, r)
|
||||
}
|
||||
})
|
||||
mux.HandleFunc("/admin", func(w http.ResponseWriter, r *http.Request) {
|
||||
http.Redirect(w, r, "/admin/", http.StatusSeeOther)
|
||||
})
|
||||
return nil
|
||||
}
|
||||
|
||||
func (a *admin) renderHome(w http.ResponseWriter, r *http.Request, svc *Service, opts CheckOptions) {
|
||||
ctx := r.Context()
|
||||
status := CheckAll(ctx, opts)
|
||||
recent, err := svc.ListClaims(ctx, m2mcore.Filter{Limit: 10})
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
data := homeData{
|
||||
page: nowPage("Дашборд", "home"),
|
||||
Status: status,
|
||||
Recent: recent.Items,
|
||||
}
|
||||
full, err := svc.ListClaims(ctx, m2mcore.Filter{Limit: 200})
|
||||
if err == nil {
|
||||
for _, c := range full.Items {
|
||||
data.Counts.Total++
|
||||
switch c.Status {
|
||||
case string(m2mcore.StateConfirmed), string(m2mcore.StateAwaitingSUB16), string(m2mcore.StateDone):
|
||||
data.Counts.Confirmed++
|
||||
case string(m2mcore.StateRejected), string(m2mcore.StateTimedOut):
|
||||
data.Counts.Failed++
|
||||
default:
|
||||
data.Counts.InProgress++
|
||||
}
|
||||
}
|
||||
}
|
||||
render(w, a.home, data)
|
||||
}
|
||||
|
||||
func (a *admin) renderClaims(w http.ResponseWriter, r *http.Request, svc *Service) {
|
||||
pageData, err := svc.ListClaims(r.Context(), m2mcore.Filter{Limit: 200})
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
render(w, a.claims, claimsData{page: nowPage("Заявки", "claims"), Items: pageData.Items})
|
||||
}
|
||||
|
||||
func (a *admin) renderClaim(w http.ResponseWriter, r *http.Request, svc *Service, id string) {
|
||||
id = path.Base(id)
|
||||
view, err := svc.GetClaim(r.Context(), id)
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
render(w, a.claim, claimData{page: nowPage("Заявка", "claims"), Claim: view})
|
||||
}
|
||||
|
||||
func (a *admin) renderStatus(w http.ResponseWriter, r *http.Request, opts CheckOptions) {
|
||||
s := CheckAll(r.Context(), opts)
|
||||
render(w, a.status, statusData{
|
||||
page: nowPage("Статус", "status"), Checks: s.Checks, CheckedAt: s.CheckedAt,
|
||||
})
|
||||
}
|
||||
|
||||
func render(w http.ResponseWriter, t *template.Template, data any) {
|
||||
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
||||
if err := t.ExecuteTemplate(w, "layout", data); err != nil {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
}
|
||||
}
|
||||
|
||||
func nowPage(title, active string) page {
|
||||
return page{Title: title, Active: active, Now: time.Now().Format("02.01.2006 15:04:05")}
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
package lkgateway
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"git.zetit.ru/zuevav/Bridge-and-Join-s/internal/m2mcore"
|
||||
)
|
||||
|
||||
// RegisterAPI вешает REST-маршруты ESIA Finance V1 на mux.
|
||||
func RegisterAPI(mux *http.ServeMux, svc *Service) {
|
||||
mux.HandleFunc("/api/v1/back_office/claims/", func(w http.ResponseWriter, r *http.Request) {
|
||||
path := strings.TrimPrefix(r.URL.Path, "/api/v1/back_office/claims/")
|
||||
switch {
|
||||
case path == "" && r.Method == http.MethodPost:
|
||||
handleCreateClaim(w, r, svc)
|
||||
case path != "" && r.Method == http.MethodGet:
|
||||
handleGetClaim(w, r, svc, path)
|
||||
case path != "" && r.Method == http.MethodPatch:
|
||||
// PATCH без id — отдельный обработчик ниже; этот блок для PATCH
|
||||
// с id, который lk-gateway сам себе бы посылал. На практике не
|
||||
// используется (callback идёт в ЛК), но реализуем по контракту.
|
||||
handlePatchClaim(w, r, svc, path)
|
||||
default:
|
||||
writeError(w, http.StatusMethodNotAllowed, "method_not_allowed", "Метод не разрешён", r.Method)
|
||||
}
|
||||
})
|
||||
|
||||
mux.HandleFunc("/api/v1/back_office/claims", func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodGet {
|
||||
writeError(w, http.StatusMethodNotAllowed, "method_not_allowed", "Метод не разрешён", r.Method)
|
||||
return
|
||||
}
|
||||
handleListClaims(w, r, svc)
|
||||
})
|
||||
}
|
||||
|
||||
func handleCreateClaim(w http.ResponseWriter, r *http.Request, svc *Service) {
|
||||
defer r.Body.Close()
|
||||
var in CreateClaimRequest
|
||||
if err := json.NewDecoder(r.Body).Decode(&in); err != nil {
|
||||
writeError(w, http.StatusBadRequest, "invalid_json", "Не смогли разобрать JSON", err.Error())
|
||||
return
|
||||
}
|
||||
out, err := svc.CreateClaim(r.Context(), in)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusUnprocessableEntity, "invalid_claim", "Заявка не прошла валидацию", err.Error())
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusCreated, out)
|
||||
}
|
||||
|
||||
func handleGetClaim(w http.ResponseWriter, r *http.Request, svc *Service, id string) {
|
||||
view, err := svc.GetClaim(r.Context(), id)
|
||||
if err != nil {
|
||||
if errors.Is(err, m2mcore.ErrNotFound) {
|
||||
writeError(w, http.StatusNotFound, "not_found", "Заявка не найдена", id)
|
||||
return
|
||||
}
|
||||
writeError(w, http.StatusInternalServerError, "internal", "Внутренняя ошибка", err.Error())
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, view)
|
||||
}
|
||||
|
||||
func handleListClaims(w http.ResponseWriter, r *http.Request, svc *Service) {
|
||||
q := r.URL.Query()
|
||||
filter := m2mcore.Filter{}
|
||||
if s := q.Get("status"); s != "" {
|
||||
st := m2mcore.State(s)
|
||||
filter.State = &st
|
||||
}
|
||||
if inv := q.Get("investor_id"); inv != "" {
|
||||
filter.InvestorID = inv
|
||||
}
|
||||
if l := q.Get("limit"); l != "" {
|
||||
if n, err := strconv.Atoi(l); err == nil && n > 0 && n <= 200 {
|
||||
filter.Limit = n
|
||||
}
|
||||
}
|
||||
if o := q.Get("offset"); o != "" {
|
||||
if n, err := strconv.Atoi(o); err == nil && n >= 0 {
|
||||
filter.Offset = n
|
||||
}
|
||||
}
|
||||
page, err := svc.ListClaims(r.Context(), filter)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "internal", "Внутренняя ошибка", err.Error())
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, page)
|
||||
}
|
||||
|
||||
func handlePatchClaim(w http.ResponseWriter, _ *http.Request, _ *Service, _ string) {
|
||||
// В сценарии M1-M2 PATCH /claims/{id} от внешней системы (как
|
||||
// callback от НРД) не используется — мы сами шлём callback в ЛК.
|
||||
// Но оставляем заглушку с 200, чтобы покрыть контракт OpenAPI.
|
||||
writeJSON(w, http.StatusOK, map[string]bool{"success": true})
|
||||
}
|
||||
@@ -0,0 +1,163 @@
|
||||
package lkgateway
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net"
|
||||
"net/http"
|
||||
"os"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Status — состояние одной проверяемой подсистемы.
|
||||
type Status struct {
|
||||
Name string `json:"name"`
|
||||
OK bool `json:"ok"`
|
||||
Message string `json:"message,omitempty"`
|
||||
Detail string `json:"detail,omitempty"`
|
||||
}
|
||||
|
||||
// SystemStatus — все проверки.
|
||||
type SystemStatus struct {
|
||||
Profile string `json:"profile"`
|
||||
Provider string `json:"crypto_provider"`
|
||||
Checks []Status `json:"checks"`
|
||||
CheckedAt time.Time `json:"checked_at"`
|
||||
}
|
||||
|
||||
// CheckOptions — что и как проверять.
|
||||
type CheckOptions struct {
|
||||
PostgresDSN string // если пусто — режим in-memory, проверки нет
|
||||
CryptoSocket string // путь до UDS crypto-service
|
||||
NSDAdapterURL string // например http://127.0.0.1:8082
|
||||
LKCallbackURL string // куда шлём callback (lk-emulator)
|
||||
Profile string // имя профиля nsdadapter (guest-gost...)
|
||||
CryptoProvider string // BJ_CRYPTO_PROVIDER (stub|cryptopro|...)
|
||||
Timeout time.Duration // таймаут на одну проверку
|
||||
}
|
||||
|
||||
// CheckAll выполняет все доступные проверки и возвращает SystemStatus.
|
||||
func CheckAll(ctx context.Context, o CheckOptions) SystemStatus {
|
||||
if o.Timeout == 0 {
|
||||
o.Timeout = 2 * time.Second
|
||||
}
|
||||
out := SystemStatus{
|
||||
Profile: o.Profile,
|
||||
Provider: o.CryptoProvider,
|
||||
CheckedAt: time.Now().UTC(),
|
||||
}
|
||||
|
||||
out.Checks = append(out.Checks, checkPostgres(ctx, o))
|
||||
out.Checks = append(out.Checks, checkCryptoSocket(o))
|
||||
out.Checks = append(out.Checks, checkNSDAdapter(ctx, o))
|
||||
out.Checks = append(out.Checks, checkLKCallback(ctx, o))
|
||||
|
||||
return out
|
||||
}
|
||||
|
||||
func checkPostgres(_ context.Context, o CheckOptions) Status {
|
||||
s := Status{Name: "postgres"}
|
||||
if o.PostgresDSN == "" {
|
||||
s.OK = true
|
||||
s.Message = "in-memory (PostgresDSN не задан, репозиторий — m2mcore.MemoryRepository)"
|
||||
return s
|
||||
}
|
||||
// На M2 здесь будет sql.Open + Ping. На текущем шаге — заглушка.
|
||||
s.OK = false
|
||||
s.Message = "PostgreSQL Repository не подключён (требуется pgx, M2-шаг-3)"
|
||||
s.Detail = "DSN: " + o.PostgresDSN
|
||||
return s
|
||||
}
|
||||
|
||||
func checkCryptoSocket(o CheckOptions) Status {
|
||||
s := Status{Name: "crypto-service (UDS)"}
|
||||
if o.CryptoSocket == "" {
|
||||
s.OK = false
|
||||
s.Message = "BJ_CRYPTO_SOCKET не задан"
|
||||
return s
|
||||
}
|
||||
info, err := os.Stat(o.CryptoSocket)
|
||||
if err != nil {
|
||||
s.OK = false
|
||||
s.Message = "сокет недоступен"
|
||||
s.Detail = err.Error()
|
||||
return s
|
||||
}
|
||||
if info.Mode()&os.ModeSocket == 0 {
|
||||
s.OK = false
|
||||
s.Message = "путь существует, но это не сокет"
|
||||
s.Detail = o.CryptoSocket
|
||||
return s
|
||||
}
|
||||
// Пробуем подключиться.
|
||||
d := net.Dialer{Timeout: o.Timeout}
|
||||
conn, err := d.Dial("unix", o.CryptoSocket)
|
||||
if err != nil {
|
||||
s.OK = false
|
||||
s.Message = "сокет существует, но не отвечает"
|
||||
s.Detail = err.Error()
|
||||
return s
|
||||
}
|
||||
_ = conn.Close()
|
||||
s.OK = true
|
||||
s.Message = "сокет открыт"
|
||||
s.Detail = o.CryptoSocket
|
||||
if o.CryptoProvider == "stub" || o.CryptoProvider == "" {
|
||||
s.Message += ", провайдер stub (реальная криптография не подключена)"
|
||||
} else {
|
||||
s.Message += ", провайдер " + o.CryptoProvider
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
func checkNSDAdapter(ctx context.Context, o CheckOptions) Status {
|
||||
s := Status{Name: "nsd-adapter (REST к ИШ)"}
|
||||
if o.NSDAdapterURL == "" {
|
||||
s.OK = true
|
||||
s.Message = "BJ_NSD_ADAPTER_URL не задан — используется mock NSDSender"
|
||||
return s
|
||||
}
|
||||
return httpHealth(ctx, o.NSDAdapterURL+"/healthz", o.Timeout, s)
|
||||
}
|
||||
|
||||
func checkLKCallback(ctx context.Context, o CheckOptions) Status {
|
||||
s := Status{Name: "lk-emulator (callback)"}
|
||||
if o.LKCallbackURL == "" {
|
||||
s.OK = false
|
||||
s.Message = "BJ_LK_CALLBACK_URL не задан — callback'и в ЛК отключены"
|
||||
return s
|
||||
}
|
||||
return httpHealth(ctx, o.LKCallbackURL+"/healthz", o.Timeout, s)
|
||||
}
|
||||
|
||||
func httpHealth(ctx context.Context, url string, timeout time.Duration, s Status) Status {
|
||||
c := &http.Client{Timeout: timeout}
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
|
||||
if err != nil {
|
||||
s.OK = false
|
||||
s.Message = "не получилось собрать запрос"
|
||||
s.Detail = err.Error()
|
||||
return s
|
||||
}
|
||||
resp, err := c.Do(req)
|
||||
if err != nil {
|
||||
s.OK = false
|
||||
s.Message = "недоступен"
|
||||
s.Detail = err.Error()
|
||||
return s
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
s.OK = false
|
||||
s.Message = "HTTP " + http.StatusText(resp.StatusCode)
|
||||
s.Detail = url
|
||||
return s
|
||||
}
|
||||
s.OK = true
|
||||
s.Message = "OK"
|
||||
s.Detail = url
|
||||
return s
|
||||
}
|
||||
|
||||
// ErrUnknown — общий placeholder.
|
||||
var ErrUnknown = errors.New("lkgateway: unknown error")
|
||||
@@ -0,0 +1,52 @@
|
||||
package lkgateway
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
// postJSON отправляет JSON через любой метод (POST/PATCH/PUT). Используется
|
||||
// для callback'ов в ЛК.
|
||||
func postJSON(ctx context.Context, c *http.Client, url, method string, body any) error {
|
||||
raw, err := json.Marshal(body)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
req, err := http.NewRequestWithContext(ctx, method, url, bytes.NewReader(raw))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
resp, err := c.Do(req)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode >= 400 {
|
||||
buf, _ := io.ReadAll(resp.Body)
|
||||
return fmt.Errorf("HTTP %d: %s", resp.StatusCode, string(buf))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// writeJSON удобный writer JSON-ответа со статусом.
|
||||
func writeJSON(w http.ResponseWriter, status int, body any) {
|
||||
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
||||
w.WriteHeader(status)
|
||||
_ = json.NewEncoder(w).Encode(body)
|
||||
}
|
||||
|
||||
// writeError формирует ErrorResponse по контракту ESIA Finance.
|
||||
func writeError(w http.ResponseWriter, status int, code, title, message string) {
|
||||
writeJSON(w, status, ErrorResponse{
|
||||
Error: true,
|
||||
Status: status,
|
||||
Code: code,
|
||||
Title: title,
|
||||
Meta: &ErrorMeta{Message: message},
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
package lkgateway
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"git.zetit.ru/zuevav/Bridge-and-Join-s/internal/m2m"
|
||||
"git.zetit.ru/zuevav/Bridge-and-Join-s/internal/m2mcore"
|
||||
)
|
||||
|
||||
// SeedStore — in-memory FansyStore с предзаполненными тестовыми данными
|
||||
// (5 клиентов с депо-счетами и портфелями), соответствующими
|
||||
// docs/fansy-contract/v1/examples/seed-data.sql. Используется в
|
||||
// dev-стенде без реальной БД.
|
||||
type SeedStore struct {
|
||||
clients map[string]*m2mcore.Client
|
||||
accounts map[string][]m2mcore.DepoAccount // by client_id
|
||||
}
|
||||
|
||||
// NewSeedStore собирает SeedStore с фиксированными тестовыми клиентами.
|
||||
func NewSeedStore() *SeedStore {
|
||||
s := &SeedStore{
|
||||
clients: make(map[string]*m2mcore.Client),
|
||||
accounts: make(map[string][]m2mcore.DepoAccount),
|
||||
}
|
||||
s.addClient("11111111-1111-1111-1111-111111111111",
|
||||
"Иванов", "Иван", "Иванович",
|
||||
m2m.DocCode21, "4512", "654321")
|
||||
s.addClient("22222222-2222-2222-2222-222222222222",
|
||||
"Петров", "Пётр", "Петрович",
|
||||
m2m.DocCode21, "4513", "654322")
|
||||
s.addClient("33333333-3333-3333-3333-333333333333",
|
||||
"Сидоров", "Сидор", "Сидорович",
|
||||
m2m.DocCode21, "4514", "654323")
|
||||
s.addClient("44444444-4444-4444-4444-444444444444",
|
||||
"Кузнецов", "Сергей", "Михайлович",
|
||||
m2m.DocCode03, "111", "222333")
|
||||
s.addClient("55555555-5555-5555-5555-555555555555",
|
||||
"Соколова", "Анна", "Викторовна",
|
||||
m2m.DocCode21, "4516", "654325")
|
||||
|
||||
s.addAccount("11111111-1111-1111-1111-111111111111",
|
||||
"DP789456", "31MC0021900000F01", "P001", "7702070139")
|
||||
s.addAccount("11111111-1111-1111-1111-111111111111",
|
||||
"AA789451", "33MC0021900000F02", "F002", "7802031669")
|
||||
s.addAccount("22222222-2222-2222-2222-222222222222",
|
||||
"DP100200", "31MC0010000000A01", "A001", "7702070139")
|
||||
s.addAccount("33333333-3333-3333-3333-333333333333",
|
||||
"DP300400", "31MC0030000000B01", "B001", "0702345678")
|
||||
s.addAccount("55555555-5555-5555-5555-555555555555",
|
||||
"DP500600", "31MC0050000000C01", "C001", "0710987654")
|
||||
|
||||
return s
|
||||
}
|
||||
|
||||
// Clients возвращает копию слайса клиентов (для UI выбора).
|
||||
func (s *SeedStore) Clients() []*m2mcore.Client {
|
||||
out := make([]*m2mcore.Client, 0, len(s.clients))
|
||||
for _, c := range s.clients {
|
||||
out = append(out, c)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func (s *SeedStore) addClient(id, last, first, middle string, doc m2m.IdentityDocumentCode, series, number string) {
|
||||
s.clients[id] = &m2mcore.Client{
|
||||
ID: id,
|
||||
LastName: last,
|
||||
FirstName: first,
|
||||
MiddleName: middle,
|
||||
Document: m2mcore.ClientDocument{
|
||||
DocumentType: doc,
|
||||
Series: series,
|
||||
Number: number,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func (s *SeedStore) addAccount(clientID, dep, acc, sec, depINN string) {
|
||||
s.accounts[clientID] = append(s.accounts[clientID], m2mcore.DepoAccount{
|
||||
ClientID: clientID,
|
||||
DeponentCode: dep,
|
||||
AccountID: m2m.AccountID(acc),
|
||||
SectionID: sec,
|
||||
DepositoryINN: m2m.OrganizationINN(depINN),
|
||||
})
|
||||
}
|
||||
|
||||
// GetClientByID — реализация FansyStore.
|
||||
func (s *SeedStore) GetClientByID(_ context.Context, id string) (*m2mcore.Client, error) {
|
||||
c, ok := s.clients[id]
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("seedstore: клиент %s не найден", id)
|
||||
}
|
||||
return c, nil
|
||||
}
|
||||
|
||||
// GetDepoAccounts — реализация FansyStore.
|
||||
func (s *SeedStore) GetDepoAccounts(_ context.Context, clientID string, _ m2m.OrganizationINN) ([]m2mcore.DepoAccount, error) {
|
||||
accs := s.accounts[clientID]
|
||||
if len(accs) == 0 {
|
||||
return nil, fmt.Errorf("seedstore: нет счетов у клиента %s", clientID)
|
||||
}
|
||||
return accs, nil
|
||||
}
|
||||
|
||||
// GetBalances — реализация FansyStore. На M2 возвращает пустой список,
|
||||
// потому что баланс проверяется при подаче заявки в самой UI (через демо-кнопку).
|
||||
func (s *SeedStore) GetBalances(_ context.Context, _ string, _ []m2m.SecurityCode) ([]m2mcore.SecurityBalance, error) {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
// Verify тип SeedStore удовлетворяет m2mcore.FansyStore.
|
||||
var _ m2mcore.FansyStore = (*SeedStore)(nil)
|
||||
@@ -0,0 +1,178 @@
|
||||
package lkgateway
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"log"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"git.zetit.ru/zuevav/Bridge-and-Join-s/internal/m2m"
|
||||
"git.zetit.ru/zuevav/Bridge-and-Join-s/internal/m2mcore"
|
||||
"git.zetit.ru/zuevav/Bridge-and-Join-s/internal/nsdadapter/mock"
|
||||
)
|
||||
|
||||
// ServerConfig — конфигурация HTTP-сервера lk-gateway.
|
||||
type ServerConfig struct {
|
||||
Addr string
|
||||
DefaultSender m2m.DeponentCode
|
||||
DefaultReceiver m2m.DeponentCode
|
||||
CheckOptions func() CheckOptions
|
||||
MockDecisionDelay time.Duration // 0 = дефолт 3 секунды
|
||||
}
|
||||
|
||||
// Server — обвязка HTTP + сервис + workers.
|
||||
type Server struct {
|
||||
cfg ServerConfig
|
||||
svc *Service
|
||||
mock *mock.Sender
|
||||
store *SeedStore
|
||||
mux *http.ServeMux
|
||||
server *http.Server
|
||||
}
|
||||
|
||||
// NewServer собирает Server с in-memory репозиторием, mock NSDSender,
|
||||
// SeedStore и REST + Admin маршрутами.
|
||||
func NewServer(cfg ServerConfig) (*Server, error) {
|
||||
store := NewSeedStore()
|
||||
mockCfg := mock.DefaultConfig()
|
||||
mockCfg.NSDSenderCode = "MC0010300000"
|
||||
if cfg.MockDecisionDelay > 0 {
|
||||
mockCfg.DecisionDelay = cfg.MockDecisionDelay
|
||||
}
|
||||
sender := mock.NewSender(mockCfg)
|
||||
|
||||
svc := NewService(Config{
|
||||
Repository: m2mcore.NewMemoryRepository(),
|
||||
Sender: sender,
|
||||
Store: store,
|
||||
Recorder: m2mcore.NewMemoryRecorder(),
|
||||
DefaultSender: cfg.DefaultSender,
|
||||
DefaultReceiver: cfg.DefaultReceiver,
|
||||
})
|
||||
|
||||
mux := http.NewServeMux()
|
||||
RegisterAPI(mux, svc)
|
||||
if cfg.CheckOptions == nil {
|
||||
cfg.CheckOptions = func() CheckOptions {
|
||||
return CheckOptions{Profile: "demo (mock NSD)", CryptoProvider: "stub"}
|
||||
}
|
||||
}
|
||||
if err := RegisterAdmin(mux, svc, cfg.CheckOptions); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
registerHealth(mux)
|
||||
registerSetCallback(mux, svc)
|
||||
registerSeedListing(mux, store)
|
||||
|
||||
return &Server{
|
||||
cfg: cfg,
|
||||
svc: svc,
|
||||
mock: sender,
|
||||
store: store,
|
||||
mux: mux,
|
||||
server: &http.Server{
|
||||
Addr: cfg.Addr,
|
||||
Handler: mux,
|
||||
ReadHeaderTimeout: 5 * time.Second,
|
||||
},
|
||||
}, nil
|
||||
}
|
||||
|
||||
// SetCallbackURL обновляет адрес, куда отправлять PATCH callback'и в ЛК.
|
||||
func (s *Server) SetCallbackURL(url string) { s.svc.callbackURL = url }
|
||||
|
||||
// Service возвращает Service для тестов.
|
||||
func (s *Server) Service() *Service { return s.svc }
|
||||
|
||||
// Mock возвращает mock-сендер.
|
||||
func (s *Server) Mock() *mock.Sender { return s.mock }
|
||||
|
||||
// Store возвращает SeedStore.
|
||||
func (s *Server) Store() *SeedStore { return s.store }
|
||||
|
||||
// Mux возвращает обработчик (для httptest).
|
||||
func (s *Server) Mux() http.Handler { return s.mux }
|
||||
|
||||
// Run поднимает HTTP-сервер и фоновый Decisions-consumer.
|
||||
// Блокируется до ctx.Done().
|
||||
func (s *Server) Run(ctx context.Context) error {
|
||||
go s.consumeDecisions(ctx)
|
||||
|
||||
errCh := make(chan error, 1)
|
||||
go func() {
|
||||
log.Printf("lk-gateway: listen %s", s.cfg.Addr)
|
||||
errCh <- s.server.ListenAndServe()
|
||||
}()
|
||||
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
shutdownCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
_ = s.server.Shutdown(shutdownCtx)
|
||||
return nil
|
||||
case err := <-errCh:
|
||||
if errors.Is(err, http.ErrServerClosed) {
|
||||
return nil
|
||||
}
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
// consumeDecisions слушает Decisions от mock и обновляет соответствующие сделки.
|
||||
func (s *Server) consumeDecisions(ctx context.Context) {
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case d := <-s.mock.Decisions():
|
||||
if d == nil {
|
||||
continue
|
||||
}
|
||||
if err := s.svc.ApplyDecision(ctx, d); err != nil {
|
||||
log.Printf("lk-gateway: ApplyDecision GUID=%s: %v", d.Header.GUID, err)
|
||||
} else {
|
||||
log.Printf("lk-gateway: Decision применён GUID=%s, callback в %s", d.Header.GUID, s.svc.callbackURL)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func registerHealth(mux *http.ServeMux) {
|
||||
mux.HandleFunc("/healthz", func(w http.ResponseWriter, _ *http.Request) {
|
||||
w.WriteHeader(http.StatusOK)
|
||||
_, _ = w.Write([]byte("ok\n"))
|
||||
})
|
||||
}
|
||||
|
||||
// registerSetCallback — служебный POST /admin/api/callback-url для
|
||||
// эмулятора ЛК, чтобы сообщить gateway свой URL.
|
||||
func registerSetCallback(mux *http.ServeMux, svc *Service) {
|
||||
mux.HandleFunc("/admin/api/callback-url", func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodPost {
|
||||
http.Error(w, "method", http.StatusMethodNotAllowed)
|
||||
return
|
||||
}
|
||||
url := r.URL.Query().Get("url")
|
||||
if url == "" {
|
||||
http.Error(w, "url required", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
svc.callbackURL = url
|
||||
w.WriteHeader(http.StatusOK)
|
||||
_, _ = w.Write([]byte("ok"))
|
||||
})
|
||||
}
|
||||
|
||||
func registerSeedListing(mux *http.ServeMux, store *SeedStore) {
|
||||
mux.HandleFunc("/admin/api/clients", func(w http.ResponseWriter, _ *http.Request) {
|
||||
type c struct {
|
||||
ID, LastName, FirstName, MiddleName string
|
||||
}
|
||||
out := make([]c, 0)
|
||||
for _, cl := range store.Clients() {
|
||||
out = append(out, c{ID: cl.ID, LastName: cl.LastName, FirstName: cl.FirstName, MiddleName: cl.MiddleName})
|
||||
}
|
||||
writeJSON(w, http.StatusOK, out)
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,255 @@
|
||||
package lkgateway_test
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.zetit.ru/zuevav/Bridge-and-Join-s/internal/lkgateway"
|
||||
)
|
||||
|
||||
func newServer(t *testing.T) *lkgateway.Server {
|
||||
t.Helper()
|
||||
srv, err := lkgateway.NewServer(lkgateway.ServerConfig{
|
||||
Addr: ":0",
|
||||
DefaultSender: "MC0079200000",
|
||||
DefaultReceiver: "MC0010300000",
|
||||
MockDecisionDelay: 50 * time.Millisecond,
|
||||
CheckOptions: func() lkgateway.CheckOptions {
|
||||
return lkgateway.CheckOptions{Profile: "test", CryptoProvider: "stub"}
|
||||
},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("NewServer: %v", err)
|
||||
}
|
||||
return srv
|
||||
}
|
||||
|
||||
func validBody() string {
|
||||
return `{
|
||||
"investor": {
|
||||
"id": "11111111-1111-1111-1111-111111111111",
|
||||
"last_name": "Иванов", "first_name": "Иван", "middle_name": "Иванович",
|
||||
"document": {"document_type": "21", "series": "4512", "number": "654321"}
|
||||
},
|
||||
"transferring_depository_inn": "0702345678",
|
||||
"receiving_depository_inn": "0710987654",
|
||||
"cost_info": {"no": {}},
|
||||
"securities": [{
|
||||
"security_code": "MM0766162534",
|
||||
"security_details": {"isin": "RU0007661625"},
|
||||
"quantity": {"whole": 1500},
|
||||
"settlement_accounts": [{
|
||||
"settlement_requisites_inn": "7702070139",
|
||||
"settlement_location": {
|
||||
"deponent_code": "DP789456", "account_id": "31MC0021900000F01", "section_id": "P001"
|
||||
}
|
||||
}]
|
||||
}],
|
||||
"signed_document": "dGVzdA==",
|
||||
"signature_format": "XMLDSig-GOST"
|
||||
}`
|
||||
}
|
||||
|
||||
func TestCreateAndGetClaim(t *testing.T) {
|
||||
srv := newServer(t)
|
||||
mux := srv.Mux()
|
||||
|
||||
w := httptest.NewRecorder()
|
||||
req := httptest.NewRequest(http.MethodPost, "/api/v1/back_office/claims/", strings.NewReader(validBody()))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
mux.ServeHTTP(w, req)
|
||||
|
||||
if w.Code != http.StatusCreated {
|
||||
t.Fatalf("POST claims: code=%d body=%s", w.Code, w.Body.String())
|
||||
}
|
||||
var created lkgateway.CreateClaimResponse
|
||||
if err := json.Unmarshal(w.Body.Bytes(), &created); err != nil {
|
||||
t.Fatalf("decode: %v body=%s", err, w.Body.String())
|
||||
}
|
||||
if created.ID == "" || !created.Success {
|
||||
t.Errorf("unexpected create response: %+v", created)
|
||||
}
|
||||
|
||||
// GET
|
||||
w2 := httptest.NewRecorder()
|
||||
req2 := httptest.NewRequest(http.MethodGet, "/api/v1/back_office/claims/"+created.ID, nil)
|
||||
mux.ServeHTTP(w2, req2)
|
||||
if w2.Code != http.StatusOK {
|
||||
t.Fatalf("GET claim: code=%d body=%s", w2.Code, w2.Body.String())
|
||||
}
|
||||
var view lkgateway.ClaimView
|
||||
if err := json.Unmarshal(w2.Body.Bytes(), &view); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if view.ID != created.ID {
|
||||
t.Errorf("view.ID = %s, ожидалось %s", view.ID, created.ID)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAdminHome(t *testing.T) {
|
||||
srv := newServer(t)
|
||||
w := httptest.NewRecorder()
|
||||
req := httptest.NewRequest(http.MethodGet, "/admin/", nil)
|
||||
srv.Mux().ServeHTTP(w, req)
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("admin home code=%d", w.Code)
|
||||
}
|
||||
body := w.Body.String()
|
||||
if !strings.Contains(body, "lk-gateway") {
|
||||
t.Errorf("в дашборде нет заголовка lk-gateway")
|
||||
}
|
||||
if !strings.Contains(body, "Состояние системы") {
|
||||
t.Errorf("в дашборде нет блока статуса")
|
||||
}
|
||||
}
|
||||
|
||||
func TestAdminStatus(t *testing.T) {
|
||||
srv := newServer(t)
|
||||
w := httptest.NewRecorder()
|
||||
req := httptest.NewRequest(http.MethodGet, "/admin/status", nil)
|
||||
srv.Mux().ServeHTTP(w, req)
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("status code=%d", w.Code)
|
||||
}
|
||||
if !strings.Contains(w.Body.String(), "postgres") {
|
||||
t.Errorf("в статусе нет проверки postgres")
|
||||
}
|
||||
}
|
||||
|
||||
func TestEndToEndFlowWithMock(t *testing.T) {
|
||||
srv := newServer(t)
|
||||
// Уменьшим задержку mock для быстрого e2e.
|
||||
// Не достаём её напрямую — пересоздадим Server со встроенными настройками
|
||||
// и проверим только что после Send статус становится submitted_to_nsd → awaiting_decision.
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
_ = ctx
|
||||
|
||||
w := httptest.NewRecorder()
|
||||
req := httptest.NewRequest(http.MethodPost, "/api/v1/back_office/claims/", strings.NewReader(validBody()))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
srv.Mux().ServeHTTP(w, req)
|
||||
if w.Code != http.StatusCreated {
|
||||
t.Fatalf("POST claims: code=%d body=%s", w.Code, w.Body.String())
|
||||
}
|
||||
var created lkgateway.CreateClaimResponse
|
||||
_ = json.Unmarshal(w.Body.Bytes(), &created)
|
||||
|
||||
if created.Status != "awaiting_decision" {
|
||||
t.Errorf("после Submit ожидалось awaiting_decision, получено %s", created.Status)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCallbackURLSetter(t *testing.T) {
|
||||
srv := newServer(t)
|
||||
w := httptest.NewRecorder()
|
||||
req := httptest.NewRequest(http.MethodPost, "/admin/api/callback-url?url=http://x.example/", nil)
|
||||
srv.Mux().ServeHTTP(w, req)
|
||||
if w.Code != http.StatusOK {
|
||||
t.Errorf("set callback url: %d", w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestListClaimsEmpty(t *testing.T) {
|
||||
srv := newServer(t)
|
||||
w := httptest.NewRecorder()
|
||||
req := httptest.NewRequest(http.MethodGet, "/api/v1/back_office/claims", nil)
|
||||
srv.Mux().ServeHTTP(w, req)
|
||||
if w.Code != http.StatusOK {
|
||||
t.Errorf("list claims empty: %d", w.Code)
|
||||
}
|
||||
var page lkgateway.ClaimsPage
|
||||
_ = json.Unmarshal(w.Body.Bytes(), &page)
|
||||
if len(page.Items) != 0 {
|
||||
t.Errorf("ожидалась пустая страница, получено %d", len(page.Items))
|
||||
}
|
||||
}
|
||||
|
||||
func TestInvalidJSON(t *testing.T) {
|
||||
srv := newServer(t)
|
||||
w := httptest.NewRecorder()
|
||||
req := httptest.NewRequest(http.MethodPost, "/api/v1/back_office/claims/", bytes.NewReader([]byte("not json")))
|
||||
srv.Mux().ServeHTTP(w, req)
|
||||
if w.Code != http.StatusBadRequest {
|
||||
t.Errorf("ожидался 400, получено %d", w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSeedClientsEndpoint(t *testing.T) {
|
||||
srv := newServer(t)
|
||||
w := httptest.NewRecorder()
|
||||
req := httptest.NewRequest(http.MethodGet, "/admin/api/clients", nil)
|
||||
srv.Mux().ServeHTTP(w, req)
|
||||
if w.Code != http.StatusOK {
|
||||
t.Errorf("clients: %d", w.Code)
|
||||
}
|
||||
var clients []map[string]any
|
||||
_ = json.Unmarshal(w.Body.Bytes(), &clients)
|
||||
if len(clients) < 5 {
|
||||
t.Errorf("ожидалось 5+ клиентов в seed, получено %d", len(clients))
|
||||
}
|
||||
}
|
||||
|
||||
func TestE2EApplyDecisionFiresCallback(t *testing.T) {
|
||||
// Поднимаем gateway in-process + http-эмулятор как callback-приёмник.
|
||||
// Дальше: POST заявки → ждём Decision из mock-канала → вручную дёргаем
|
||||
// ApplyDecision → проверяем что emulator получил callback.
|
||||
gw := newServer(t)
|
||||
|
||||
receivedCallback := make(chan map[string]any, 1)
|
||||
emulator := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method == http.MethodPatch && strings.HasPrefix(r.URL.Path, "/api/v1/back_office/claims/") {
|
||||
var payload map[string]any
|
||||
_ = json.NewDecoder(r.Body).Decode(&payload)
|
||||
select {
|
||||
case receivedCallback <- payload:
|
||||
default:
|
||||
}
|
||||
w.WriteHeader(http.StatusOK)
|
||||
return
|
||||
}
|
||||
w.WriteHeader(http.StatusOK)
|
||||
}))
|
||||
defer emulator.Close()
|
||||
gw.SetCallbackURL(emulator.URL)
|
||||
|
||||
// Подаём заявку через mux (без отдельного httptest.NewServer для gateway).
|
||||
w := httptest.NewRecorder()
|
||||
req := httptest.NewRequest(http.MethodPost, "/api/v1/back_office/claims/", strings.NewReader(validBody()))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
gw.Mux().ServeHTTP(w, req)
|
||||
if w.Code != http.StatusCreated {
|
||||
t.Fatalf("POST claims: %d", w.Code)
|
||||
}
|
||||
|
||||
// Mock эмитит Decision через MockDecisionDelay (50мс). Дождёмся его и
|
||||
// прокинем в ApplyDecision — этого делает фоновый воркер, который в
|
||||
// этом тесте не запущен (Run не вызывается).
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
|
||||
defer cancel()
|
||||
|
||||
select {
|
||||
case d := <-gw.Mock().Decisions():
|
||||
if err := gw.Service().ApplyDecision(ctx, d); err != nil {
|
||||
t.Fatalf("ApplyDecision: %v", err)
|
||||
}
|
||||
case <-ctx.Done():
|
||||
t.Fatal("Decision из mock не пришёл")
|
||||
}
|
||||
|
||||
select {
|
||||
case cb := <-receivedCallback:
|
||||
status, _ := cb["new_status"].(string)
|
||||
if status != "confirmed" {
|
||||
t.Errorf("ожидался callback со статусом confirmed, получено %s", status)
|
||||
}
|
||||
case <-time.After(2 * time.Second):
|
||||
t.Fatal("callback в эмулятор не пришёл")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,386 @@
|
||||
package lkgateway
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log"
|
||||
"net/http"
|
||||
"sort"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"git.zetit.ru/zuevav/Bridge-and-Join-s/internal/m2m"
|
||||
"git.zetit.ru/zuevav/Bridge-and-Join-s/internal/m2mcore"
|
||||
)
|
||||
|
||||
// Service — бизнес-логика lk-gateway: преобразует DTO в доменные сущности
|
||||
// m2mcore, оркестрирует FSM сделки, эмитит callback'и в ЛК.
|
||||
type Service struct {
|
||||
repo m2mcore.Repository
|
||||
sender m2mcore.NSDSender
|
||||
store m2mcore.FansyStore
|
||||
recorder *m2mcore.MemoryRecorder
|
||||
defaultSender m2m.DeponentCode
|
||||
defaultReceiver m2m.DeponentCode
|
||||
callbackURL string
|
||||
httpClient *http.Client
|
||||
|
||||
mu sync.RWMutex
|
||||
claimToID map[string]string // claim public ID -> internal deal ID
|
||||
}
|
||||
|
||||
// Config — параметры сервиса.
|
||||
type Config struct {
|
||||
Repository m2mcore.Repository
|
||||
Sender m2mcore.NSDSender
|
||||
Store m2mcore.FansyStore
|
||||
Recorder *m2mcore.MemoryRecorder
|
||||
DefaultSender m2m.DeponentCode
|
||||
DefaultReceiver m2m.DeponentCode
|
||||
CallbackURL string
|
||||
}
|
||||
|
||||
// NewService собирает сервис.
|
||||
func NewService(cfg Config) *Service {
|
||||
if cfg.Recorder == nil {
|
||||
cfg.Recorder = m2mcore.NewMemoryRecorder()
|
||||
}
|
||||
return &Service{
|
||||
repo: cfg.Repository,
|
||||
sender: cfg.Sender,
|
||||
store: cfg.Store,
|
||||
recorder: cfg.Recorder,
|
||||
defaultSender: cfg.DefaultSender,
|
||||
defaultReceiver: cfg.DefaultReceiver,
|
||||
callbackURL: cfg.CallbackURL,
|
||||
httpClient: &http.Client{Timeout: 5 * time.Second},
|
||||
claimToID: make(map[string]string),
|
||||
}
|
||||
}
|
||||
|
||||
// CreateClaim принимает DTO заявки, формирует M2MTransferRequest,
|
||||
// создаёт сделку и отправляет в НРД.
|
||||
func (s *Service) CreateClaim(ctx context.Context, in CreateClaimRequest) (CreateClaimResponse, error) {
|
||||
domainClaim, err := dtoToClaim(in)
|
||||
if err != nil {
|
||||
return CreateClaimResponse{}, fmt.Errorf("lkgateway: dtoToClaim: %w", err)
|
||||
}
|
||||
|
||||
req, err := m2mcore.EnrichRequest(ctx, s.store, domainClaim, m2mcore.SenderReceiver{
|
||||
SenderCode: s.defaultSender,
|
||||
ReceiverCode: s.defaultReceiver,
|
||||
})
|
||||
if err != nil {
|
||||
return CreateClaimResponse{}, fmt.Errorf("lkgateway: EnrichRequest: %w", err)
|
||||
}
|
||||
|
||||
deal, err := m2mcore.NewDeal(req.Header.GUID, in.Investor.ID, []byte(in.SignedDocument))
|
||||
if err != nil {
|
||||
return CreateClaimResponse{}, fmt.Errorf("lkgateway: NewDeal: %w", err)
|
||||
}
|
||||
saved, err := s.repo.Create(ctx, deal)
|
||||
if err != nil {
|
||||
return CreateClaimResponse{}, fmt.Errorf("lkgateway: repo.Create: %w", err)
|
||||
}
|
||||
|
||||
if err := saved.Validate(ctx, req); err != nil {
|
||||
return CreateClaimResponse{}, fmt.Errorf("lkgateway: deal.Validate: %w", err)
|
||||
}
|
||||
|
||||
resp, err := s.sender.Send(ctx, req)
|
||||
if err != nil {
|
||||
return CreateClaimResponse{}, fmt.Errorf("lkgateway: sender.Send: %w", err)
|
||||
}
|
||||
saved.Response = resp
|
||||
|
||||
if err := saved.Submit(ctx); err != nil {
|
||||
return CreateClaimResponse{}, fmt.Errorf("lkgateway: deal.Submit: %w", err)
|
||||
}
|
||||
if err := s.repo.Update(ctx, saved); err != nil {
|
||||
return CreateClaimResponse{}, fmt.Errorf("lkgateway: repo.Update: %w", err)
|
||||
}
|
||||
s.recorder.IncDeal(saved.State)
|
||||
s.mu.Lock()
|
||||
s.claimToID[saved.ID] = saved.ID
|
||||
s.mu.Unlock()
|
||||
|
||||
return CreateClaimResponse{
|
||||
ID: saved.ID,
|
||||
Status: string(saved.State),
|
||||
CreatedAt: saved.CreatedAt,
|
||||
Success: true,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// GetClaim возвращает полную карточку заявки.
|
||||
func (s *Service) GetClaim(ctx context.Context, id string) (ClaimView, error) {
|
||||
deal, err := s.repo.GetByID(ctx, id)
|
||||
if err != nil {
|
||||
return ClaimView{}, err
|
||||
}
|
||||
return dealToView(deal), nil
|
||||
}
|
||||
|
||||
// ListClaims возвращает страницу заявок.
|
||||
func (s *Service) ListClaims(ctx context.Context, filter m2mcore.Filter) (ClaimsPage, error) {
|
||||
if filter.Limit == 0 {
|
||||
filter.Limit = 50
|
||||
}
|
||||
deals, err := s.repo.List(ctx, filter)
|
||||
if err != nil {
|
||||
return ClaimsPage{}, err
|
||||
}
|
||||
sort.Slice(deals, func(i, j int) bool { return deals[i].CreatedAt.After(deals[j].CreatedAt) })
|
||||
items := make([]ClaimView, 0, len(deals))
|
||||
for _, d := range deals {
|
||||
items = append(items, dealToView(d))
|
||||
}
|
||||
return ClaimsPage{Items: items, Total: len(items), Limit: filter.Limit, Offset: filter.Offset}, nil
|
||||
}
|
||||
|
||||
// ApplyDecision принимает Decision (из mock-NSDSender или реального адаптера),
|
||||
// обновляет соответствующую сделку и шлёт callback в ЛК.
|
||||
func (s *Service) ApplyDecision(ctx context.Context, decision *m2m.M2MTransferDecision) error {
|
||||
if decision == nil {
|
||||
return errors.New("lkgateway: ApplyDecision: decision=nil")
|
||||
}
|
||||
deal, err := s.repo.GetByGUID(ctx, decision.Header.GUID)
|
||||
if err != nil {
|
||||
return fmt.Errorf("lkgateway: GetByGUID: %w", err)
|
||||
}
|
||||
if err := deal.ReceiveDecision(ctx, decision); err != nil {
|
||||
return fmt.Errorf("lkgateway: ReceiveDecision: %w", err)
|
||||
}
|
||||
if err := s.repo.Update(ctx, deal); err != nil {
|
||||
return fmt.Errorf("lkgateway: repo.Update: %w", err)
|
||||
}
|
||||
s.recorder.IncDeal(deal.State)
|
||||
|
||||
if s.callbackURL != "" {
|
||||
s.sendCallback(ctx, deal)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// sendCallback отправляет PATCH в ЛК с обновлением статуса.
|
||||
func (s *Service) sendCallback(ctx context.Context, deal *m2mcore.Deal) {
|
||||
cb := callbackForDeal(deal)
|
||||
if err := postJSON(ctx, s.httpClient, s.callbackURL+"/api/v1/back_office/claims/"+deal.ID, "PATCH", cb); err != nil {
|
||||
log.Printf("lkgateway: callback в ЛК упал: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// Recorder возвращает экспонируемый Recorder для admin-страницы.
|
||||
func (s *Service) Recorder() *m2mcore.MemoryRecorder { return s.recorder }
|
||||
|
||||
// Repo возвращает Repository (для админских проверок).
|
||||
func (s *Service) Repo() m2mcore.Repository { return s.repo }
|
||||
|
||||
// Внутренние преобразования и хелперы.
|
||||
|
||||
func dtoToClaim(in CreateClaimRequest) (m2mcore.ClaimInput, error) {
|
||||
out := m2mcore.ClaimInput{
|
||||
InvestorClientID: in.Investor.ID,
|
||||
TransferringDepositoryINN: m2m.OrganizationINN(in.TransferringDepositoryINN),
|
||||
ReceivingDepositoryINN: m2m.OrganizationINN(in.ReceivingDepositoryINN),
|
||||
}
|
||||
// CostInfo
|
||||
if in.CostInfo.Yes != nil {
|
||||
out.CostInfo = m2m.CostInfo{Yes: &m2m.CostInfoYes{Code: m2m.DeponentCode(in.CostInfo.Yes.Code)}}
|
||||
} else {
|
||||
out.CostInfo = m2m.CostInfo{No: &m2m.CostInfoNo{}}
|
||||
}
|
||||
// IIA
|
||||
if in.IIAAgreement != nil {
|
||||
out.IIAAgreement = &m2m.IIAAgreementDetails{
|
||||
AgreementType: m2m.IIAContractType(in.IIAAgreement.AgreementType),
|
||||
AgreementNumber: in.IIAAgreement.AgreementNumber,
|
||||
AgreementDate: in.IIAAgreement.AgreementDate,
|
||||
BrokerINN: m2m.OrganizationINN(in.IIAAgreement.BrokerINN),
|
||||
}
|
||||
}
|
||||
// Securities
|
||||
for _, sec := range in.Securities {
|
||||
ds, err := dtoSecurityDetails(sec.SecurityDetails)
|
||||
if err != nil {
|
||||
return m2mcore.ClaimInput{}, err
|
||||
}
|
||||
q, err := dtoQuantity(sec.Quantity)
|
||||
if err != nil {
|
||||
return m2mcore.ClaimInput{}, err
|
||||
}
|
||||
out.Securities = append(out.Securities, m2mcore.ClaimSecurityInput{
|
||||
SecurityCode: m2m.SecurityCode(sec.SecurityCode),
|
||||
Details: ds,
|
||||
Quantity: q,
|
||||
})
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func dtoSecurityDetails(in SecurityDetails) (m2m.SecurityDetails, error) {
|
||||
if in.ISIN != "" {
|
||||
isin := m2m.ISIN(in.ISIN)
|
||||
return m2m.SecurityDetails{ISIN: &isin}, nil
|
||||
}
|
||||
if in.SecurityInfo != nil {
|
||||
si := &m2m.SecurityDescription{
|
||||
SecurityClassification: m2m.SecurityClassification(in.SecurityInfo.Classification),
|
||||
SecurityCategory: m2m.SecurityCategory(in.SecurityInfo.Category),
|
||||
SecurityType: in.SecurityInfo.SecurityType,
|
||||
SecuritySeries: in.SecurityInfo.SecuritySeries,
|
||||
}
|
||||
if in.SecurityInfo.IdentificationDetails.RegNumber != "" {
|
||||
rn := in.SecurityInfo.IdentificationDetails.RegNumber
|
||||
si.IdentificationDetails = m2m.IdentificationDetails{RegNumber: &rn}
|
||||
}
|
||||
if in.SecurityInfo.IdentificationDetails.FundShares != nil {
|
||||
si.IdentificationDetails = m2m.IdentificationDetails{
|
||||
FundShares: &m2m.FundShares{
|
||||
RegNumber: in.SecurityInfo.IdentificationDetails.FundShares.RegNumber,
|
||||
Class: in.SecurityInfo.IdentificationDetails.FundShares.Class,
|
||||
},
|
||||
}
|
||||
}
|
||||
return m2m.SecurityDetails{SecurityInfo: si}, nil
|
||||
}
|
||||
return m2m.SecurityDetails{}, errors.New("lkgateway: SecurityDetails — задайте isin или security_info")
|
||||
}
|
||||
|
||||
func dtoQuantity(in Quantity) (m2m.Quantity, error) {
|
||||
if in.Whole > 0 {
|
||||
w := in.Whole
|
||||
return m2m.Quantity{Whole: &w}, nil
|
||||
}
|
||||
if in.Fractional != "" {
|
||||
f := m2m.Decimal16(in.Fractional)
|
||||
return m2m.Quantity{Fractional: &f}, nil
|
||||
}
|
||||
return m2m.Quantity{}, errors.New("lkgateway: Quantity — задайте whole или fractional")
|
||||
}
|
||||
|
||||
func dealToView(d *m2mcore.Deal) ClaimView {
|
||||
out := ClaimView{
|
||||
ID: d.ID,
|
||||
Status: string(d.State),
|
||||
CreatedAt: d.CreatedAt,
|
||||
UpdatedAt: d.UpdatedAt,
|
||||
M2MGUID: d.GUID,
|
||||
}
|
||||
for _, st := range d.Stages {
|
||||
out.Stages = append(out.Stages, StageView{
|
||||
State: string(st.State), EnteredAt: st.EnteredAt, LeftAt: st.LeftAt, Reason: st.Reason,
|
||||
})
|
||||
}
|
||||
if d.Request != nil {
|
||||
out.TransferringDepositoryINN = string(d.Request.Data.TransferringDepository.INN)
|
||||
out.ReceivingDepositoryINN = string(d.Request.Data.ReceivingDepository.INN)
|
||||
ii := d.Request.Data.InvestorInformation
|
||||
out.Investor = Investor{
|
||||
LastName: ii.LastName, FirstName: ii.FirstName, MiddleName: ii.MiddleName,
|
||||
Document: Document{
|
||||
DocumentType: string(ii.IdentityDocument.DocumentType),
|
||||
Number: string(ii.IdentityDocument.DocumentNumber),
|
||||
},
|
||||
}
|
||||
if ii.IdentityDocument.DocumentSeries != nil {
|
||||
out.Investor.Document.Series = string(*ii.IdentityDocument.DocumentSeries)
|
||||
}
|
||||
if d.Request.Header.CostInfo.Yes != nil {
|
||||
out.CostInfo = CostInfo{Yes: &CostInfoYes{Code: string(d.Request.Header.CostInfo.Yes.Code)}}
|
||||
} else if d.Request.Header.CostInfo.No != nil {
|
||||
empty := struct{}{}
|
||||
out.CostInfo = CostInfo{No: &empty}
|
||||
}
|
||||
if d.Request.Header.IIAAgreementDetails != nil {
|
||||
out.IIAAgreement = &IIAAgreement{
|
||||
AgreementType: string(d.Request.Header.IIAAgreementDetails.AgreementType),
|
||||
AgreementNumber: d.Request.Header.IIAAgreementDetails.AgreementNumber,
|
||||
AgreementDate: d.Request.Header.IIAAgreementDetails.AgreementDate,
|
||||
BrokerINN: string(d.Request.Header.IIAAgreementDetails.BrokerINN),
|
||||
}
|
||||
}
|
||||
}
|
||||
if d.Response != nil {
|
||||
out.M2MResponse = responseToView(d.Response)
|
||||
}
|
||||
if d.Decision != nil {
|
||||
out.M2MDecision = decisionToView(d.Decision)
|
||||
}
|
||||
if d.State != m2mcore.StateDraft {
|
||||
cb := callbackForDeal(d)
|
||||
out.LastCallback = &cb
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func responseToView(r *m2m.M2MTransferResponse) *NSDResponseView {
|
||||
v := &NSDResponseView{
|
||||
GUID: string(r.GUID),
|
||||
StatusCode: string(r.StatusCode),
|
||||
}
|
||||
for _, e := range r.Responses {
|
||||
ent := NSDResponseEntry{Code: e.Code, Text: e.Text}
|
||||
if e.ReferenceID != nil {
|
||||
ent.ReferenceID = string(*e.ReferenceID)
|
||||
}
|
||||
v.Responses = append(v.Responses, ent)
|
||||
}
|
||||
return v
|
||||
}
|
||||
|
||||
func decisionToView(d *m2m.M2MTransferDecision) *NSDDecisionView {
|
||||
v := &NSDDecisionView{GUID: string(d.Header.GUID)}
|
||||
for _, sec := range d.Data.Securities {
|
||||
entry := NSDDecisionSecurity{ReferenceID: string(sec.ReferenceID)}
|
||||
if sec.TransferDecision.Confirmation != nil {
|
||||
entry.Outcome = "confirmed"
|
||||
} else if sec.TransferDecision.Rejection != nil {
|
||||
entry.Outcome = "rejected"
|
||||
entry.RejectCodes = sec.TransferDecision.Rejection.Codes
|
||||
}
|
||||
v.Securities = append(v.Securities, entry)
|
||||
}
|
||||
return v
|
||||
}
|
||||
|
||||
func callbackForDeal(d *m2mcore.Deal) StatusCallback {
|
||||
cb := StatusCallback{
|
||||
ClaimID: d.ID,
|
||||
NewStatus: string(d.State),
|
||||
UpdatedAt: d.UpdatedAt,
|
||||
}
|
||||
if d.Decision != nil {
|
||||
cb.NSDResponse = nsdResponseFromDecision(d.Decision)
|
||||
if d.State == m2mcore.StateRejected {
|
||||
for _, sec := range d.Decision.Data.Securities {
|
||||
if sec.TransferDecision.Rejection != nil && len(sec.TransferDecision.Rejection.Codes) > 0 {
|
||||
cb.ReasonCode = sec.TransferDecision.Rejection.Codes[0]
|
||||
cb.ReasonText = "Отказ принимающей стороны (mock)"
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
} else if d.Response != nil {
|
||||
cb.NSDResponse = responseToView(d.Response)
|
||||
}
|
||||
return cb
|
||||
}
|
||||
|
||||
func nsdResponseFromDecision(d *m2m.M2MTransferDecision) *NSDResponseView {
|
||||
v := &NSDResponseView{GUID: string(d.Header.GUID), StatusCode: string(m2m.StatusInfo)}
|
||||
for _, sec := range d.Data.Securities {
|
||||
ref := string(sec.ReferenceID)
|
||||
ent := NSDResponseEntry{ReferenceID: ref}
|
||||
if sec.TransferDecision.Confirmation != nil {
|
||||
ent.Code = "01"
|
||||
ent.Text = "Подтверждение принимающей стороны."
|
||||
} else if sec.TransferDecision.Rejection != nil {
|
||||
ent.Code = "07"
|
||||
ent.Text = "Отказ принимающей стороны."
|
||||
}
|
||||
v.Responses = append(v.Responses, ent)
|
||||
}
|
||||
return v
|
||||
}
|
||||
@@ -0,0 +1,211 @@
|
||||
// Package lkgateway реализует REST API контракта ESIA Finance V1
|
||||
// (docs/lk-contract/v1/openapi.yaml) и admin web-интерфейс.
|
||||
package lkgateway
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"git.zetit.ru/zuevav/Bridge-and-Join-s/internal/m2m"
|
||||
)
|
||||
|
||||
// CreateClaimRequest — DTO входа POST /api/v1/back_office/claims/.
|
||||
type CreateClaimRequest struct {
|
||||
Investor Investor `json:"investor"`
|
||||
TransferringDepositoryINN string `json:"transferring_depository_inn"`
|
||||
ReceivingDepositoryINN string `json:"receiving_depository_inn"`
|
||||
CostInfo CostInfo `json:"cost_info"`
|
||||
IIAAgreement *IIAAgreement `json:"iia_agreement,omitempty"`
|
||||
Securities []ClaimSec `json:"securities"`
|
||||
SignedDocument string `json:"signed_document"`
|
||||
SignatureFormat string `json:"signature_format"`
|
||||
}
|
||||
|
||||
// Investor — анкета.
|
||||
type Investor struct {
|
||||
ID string `json:"id,omitempty"`
|
||||
LastName string `json:"last_name"`
|
||||
FirstName string `json:"first_name"`
|
||||
MiddleName string `json:"middle_name,omitempty"`
|
||||
Document Document `json:"document"`
|
||||
}
|
||||
|
||||
// Document — удостоверение личности.
|
||||
type Document struct {
|
||||
DocumentType string `json:"document_type"`
|
||||
Series string `json:"series,omitempty"`
|
||||
Number string `json:"number"`
|
||||
}
|
||||
|
||||
// CostInfo — choice yes|no.
|
||||
type CostInfo struct {
|
||||
Yes *CostInfoYes `json:"yes,omitempty"`
|
||||
No *struct{} `json:"no,omitempty"`
|
||||
}
|
||||
|
||||
// CostInfoYes — учёт ведётся, с кодом депонента-источника.
|
||||
type CostInfoYes struct {
|
||||
Code string `json:"code"`
|
||||
}
|
||||
|
||||
// IIAAgreement — реквизиты договора ИИС.
|
||||
type IIAAgreement struct {
|
||||
AgreementType string `json:"agreement_type"`
|
||||
AgreementNumber string `json:"agreement_number"`
|
||||
AgreementDate string `json:"agreement_date"`
|
||||
BrokerINN string `json:"broker_inn"`
|
||||
}
|
||||
|
||||
// ClaimSec — одна ЦБ в заявке.
|
||||
type ClaimSec struct {
|
||||
SecurityCode string `json:"security_code"`
|
||||
SecurityDetails SecurityDetails `json:"security_details"`
|
||||
Quantity Quantity `json:"quantity"`
|
||||
SettlementAccounts []SettlementAccount `json:"settlement_accounts"`
|
||||
}
|
||||
|
||||
// SecurityDetails — choice isin|security_info.
|
||||
type SecurityDetails struct {
|
||||
ISIN string `json:"isin,omitempty"`
|
||||
SecurityInfo *SecurityInfo `json:"security_info,omitempty"`
|
||||
}
|
||||
|
||||
// SecurityInfo — описание ЦБ без ISIN.
|
||||
type SecurityInfo struct {
|
||||
Classification string `json:"classification"`
|
||||
Category string `json:"category"`
|
||||
SecurityType string `json:"security_type,omitempty"`
|
||||
SecuritySeries string `json:"security_series,omitempty"`
|
||||
IdentificationDetails IdentificationDetails `json:"identification_details"`
|
||||
}
|
||||
|
||||
// IdentificationDetails — choice reg_number|fund_shares.
|
||||
type IdentificationDetails struct {
|
||||
RegNumber string `json:"reg_number,omitempty"`
|
||||
FundShares *FundShares `json:"fund_shares,omitempty"`
|
||||
}
|
||||
|
||||
// FundShares — ПИФ.
|
||||
type FundShares struct {
|
||||
RegNumber string `json:"reg_number"`
|
||||
Class string `json:"class,omitempty"`
|
||||
}
|
||||
|
||||
// Quantity — choice whole|fractional.
|
||||
type Quantity struct {
|
||||
Whole uint64 `json:"whole,omitempty"`
|
||||
Fractional string `json:"fractional,omitempty"`
|
||||
}
|
||||
|
||||
// SettlementAccount — реквизиты счёта.
|
||||
type SettlementAccount struct {
|
||||
SettlementRequisitesINN string `json:"settlement_requisites_inn"`
|
||||
SettlementLocation SettlementLocation `json:"settlement_location"`
|
||||
}
|
||||
|
||||
// SettlementLocation — место хранения.
|
||||
type SettlementLocation struct {
|
||||
DeponentCode string `json:"deponent_code"`
|
||||
AccountID string `json:"account_id"`
|
||||
SectionID string `json:"section_id"`
|
||||
}
|
||||
|
||||
// CreateClaimResponse — DTO ответа POST.
|
||||
type CreateClaimResponse struct {
|
||||
ID string `json:"id"`
|
||||
Status string `json:"status"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
Success bool `json:"success"`
|
||||
}
|
||||
|
||||
// ClaimView — полная заявка с историей (GET и admin).
|
||||
type ClaimView struct {
|
||||
ID string `json:"id"`
|
||||
Status string `json:"status"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
Investor Investor `json:"investor"`
|
||||
TransferringDepositoryINN string `json:"transferring_depository_inn"`
|
||||
ReceivingDepositoryINN string `json:"receiving_depository_inn"`
|
||||
CostInfo CostInfo `json:"cost_info"`
|
||||
IIAAgreement *IIAAgreement `json:"iia_agreement,omitempty"`
|
||||
Securities []ClaimSec `json:"securities"`
|
||||
LastCallback *StatusCallback `json:"last_callback,omitempty"`
|
||||
Stages []StageView `json:"stages,omitempty"`
|
||||
M2MGUID m2m.UUID `json:"m2m_guid,omitempty"`
|
||||
M2MResponse *NSDResponseView `json:"m2m_response,omitempty"`
|
||||
M2MDecision *NSDDecisionView `json:"m2m_decision,omitempty"`
|
||||
}
|
||||
|
||||
// StageView — точка истории FSM для UI.
|
||||
type StageView struct {
|
||||
State string `json:"state"`
|
||||
EnteredAt time.Time `json:"entered_at"`
|
||||
LeftAt *time.Time `json:"left_at,omitempty"`
|
||||
Reason string `json:"reason,omitempty"`
|
||||
}
|
||||
|
||||
// StatusCallback — callback статуса от lk-gateway к ЛК.
|
||||
type StatusCallback struct {
|
||||
ClaimID string `json:"claim_id"`
|
||||
NewStatus string `json:"new_status"`
|
||||
ReasonCode string `json:"reason_code,omitempty"`
|
||||
ReasonText string `json:"reason_text,omitempty"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
NSDResponse *NSDResponseView `json:"nsd_response,omitempty"`
|
||||
}
|
||||
|
||||
// NSDResponseView — сжатое представление M2MTransferResponse для UI/callback.
|
||||
type NSDResponseView struct {
|
||||
GUID string `json:"guid"`
|
||||
StatusCode string `json:"status_code"`
|
||||
Responses []NSDResponseEntry `json:"responses"`
|
||||
}
|
||||
|
||||
// NSDResponseEntry — одна запись Response.
|
||||
type NSDResponseEntry struct {
|
||||
ReferenceID string `json:"reference_id,omitempty"`
|
||||
Code string `json:"code"`
|
||||
Text string `json:"text,omitempty"`
|
||||
}
|
||||
|
||||
// NSDDecisionView — сжатое представление M2MTransferDecision для UI.
|
||||
type NSDDecisionView struct {
|
||||
GUID string `json:"guid"`
|
||||
Securities []NSDDecisionSecurity `json:"securities"`
|
||||
}
|
||||
|
||||
// NSDDecisionSecurity — решение по одной ЦБ.
|
||||
type NSDDecisionSecurity struct {
|
||||
ReferenceID string `json:"reference_id"`
|
||||
Outcome string `json:"outcome"` // "confirmed" | "rejected"
|
||||
RejectCodes []string `json:"reject_codes,omitempty"`
|
||||
}
|
||||
|
||||
// ErrorResponse — формат ошибки, идентичный ESIA Finance.
|
||||
type ErrorResponse struct {
|
||||
Error bool `json:"error"`
|
||||
Status int `json:"status"`
|
||||
Code string `json:"code"`
|
||||
Title string `json:"title"`
|
||||
Meta *ErrorMeta `json:"meta,omitempty"`
|
||||
}
|
||||
|
||||
// ErrorMeta — детали ошибки.
|
||||
type ErrorMeta struct {
|
||||
Message string `json:"message,omitempty"`
|
||||
Errors []FieldErrorDetail `json:"errors,omitempty"`
|
||||
}
|
||||
|
||||
// FieldErrorDetail — ошибка по конкретному полю.
|
||||
type FieldErrorDetail struct {
|
||||
Field string `json:"field"`
|
||||
Message string `json:"message"`
|
||||
}
|
||||
|
||||
// ClaimsPage — постраничная выдача.
|
||||
type ClaimsPage struct {
|
||||
Items []ClaimView `json:"items"`
|
||||
Total int `json:"total"`
|
||||
Limit int `json:"limit"`
|
||||
Offset int `json:"offset"`
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
{{define "content"}}
|
||||
<div class="card">
|
||||
<h2>Заявка <code>{{slice .Claim.ID 0 8}}</code> · <span class="badge {{.Claim.Status}}">{{.Claim.Status}}</span></h2>
|
||||
<table>
|
||||
<tr><td style="width:200px" class="muted">Создана</td><td>{{.Claim.CreatedAt.Format "02.01.2006 15:04:05"}}</td></tr>
|
||||
<tr><td class="muted">Обновлена</td><td>{{.Claim.UpdatedAt.Format "02.01.2006 15:04:05"}}</td></tr>
|
||||
<tr><td class="muted">M2M GUID</td><td><code>{{.Claim.M2MGUID}}</code></td></tr>
|
||||
<tr><td class="muted">Инвестор</td><td>{{.Claim.Investor.LastName}} {{.Claim.Investor.FirstName}} {{.Claim.Investor.MiddleName}}</td></tr>
|
||||
<tr><td class="muted">Документ</td><td>тип {{.Claim.Investor.Document.DocumentType}}, серия {{.Claim.Investor.Document.Series}}, номер {{.Claim.Investor.Document.Number}}</td></tr>
|
||||
<tr><td class="muted">Передающий депозитарий</td><td><code>ИНН {{.Claim.TransferringDepositoryINN}}</code></td></tr>
|
||||
<tr><td class="muted">Принимающий депозитарий</td><td><code>ИНН {{.Claim.ReceivingDepositoryINN}}</code></td></tr>
|
||||
{{if .Claim.IIAAgreement}}
|
||||
<tr><td class="muted">ИИС</td><td>{{.Claim.IIAAgreement.AgreementType}} № {{.Claim.IIAAgreement.AgreementNumber}} от {{.Claim.IIAAgreement.AgreementDate}}, брокер ИНН {{.Claim.IIAAgreement.BrokerINN}}</td></tr>
|
||||
{{end}}
|
||||
</table>
|
||||
</div>
|
||||
|
||||
<div class="card">
|
||||
<h2>Ценные бумаги ({{len .Claim.Securities}})</h2>
|
||||
<table>
|
||||
<thead><tr><th>Код</th><th>ISIN / описание</th><th>Количество</th><th>Счетов депо</th></tr></thead>
|
||||
<tbody>
|
||||
{{range .Claim.Securities}}
|
||||
<tr>
|
||||
<td><code>{{.SecurityCode}}</code></td>
|
||||
<td>{{if .SecurityDetails.ISIN}}<code>{{.SecurityDetails.ISIN}}</code>{{else if .SecurityDetails.SecurityInfo}}{{.SecurityDetails.SecurityInfo.Classification}} / {{.SecurityDetails.SecurityInfo.Category}}{{if .SecurityDetails.SecurityInfo.IdentificationDetails.FundShares}} · ПИФ {{.SecurityDetails.SecurityInfo.IdentificationDetails.FundShares.RegNumber}} класс {{.SecurityDetails.SecurityInfo.IdentificationDetails.FundShares.Class}}{{end}}{{end}}</td>
|
||||
<td>{{if .Quantity.Whole}}{{.Quantity.Whole}}{{else}}{{.Quantity.Fractional}}{{end}}</td>
|
||||
<td>{{len .SettlementAccounts}}</td>
|
||||
</tr>
|
||||
{{end}}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
<div class="card">
|
||||
<h2>История FSM</h2>
|
||||
<table>
|
||||
<thead><tr><th>Состояние</th><th>Вошли</th><th>Вышли</th><th>Причина</th></tr></thead>
|
||||
<tbody>
|
||||
{{range .Claim.Stages}}
|
||||
<tr>
|
||||
<td><span class="badge {{.State}}">{{.State}}</span></td>
|
||||
<td>{{.EnteredAt.Format "15:04:05.000"}}</td>
|
||||
<td>{{if .LeftAt}}{{.LeftAt.Format "15:04:05.000"}}{{else}}<span class="muted">сейчас</span>{{end}}</td>
|
||||
<td class="muted">{{.Reason}}</td>
|
||||
</tr>
|
||||
{{end}}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
{{if .Claim.M2MResponse}}
|
||||
<div class="card">
|
||||
<h2>Ответ НРД (M2MTransferResponse)</h2>
|
||||
<p class="muted">GUID <code>{{.Claim.M2MResponse.GUID}}</code> · Status <code>{{.Claim.M2MResponse.StatusCode}}</code></p>
|
||||
<table>
|
||||
<thead><tr><th>ReferenceID</th><th>Код</th><th>Текст</th></tr></thead>
|
||||
<tbody>
|
||||
{{range .Claim.M2MResponse.Responses}}
|
||||
<tr><td><code>{{.ReferenceID}}</code></td><td>{{.Code}}</td><td>{{.Text}}</td></tr>
|
||||
{{end}}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
{{end}}
|
||||
|
||||
{{if .Claim.M2MDecision}}
|
||||
<div class="card">
|
||||
<h2>Решение принимающей стороны (M2MTransferDecision)</h2>
|
||||
<p class="muted">GUID <code>{{.Claim.M2MDecision.GUID}}</code></p>
|
||||
<table>
|
||||
<thead><tr><th>ReferenceID</th><th>Решение</th><th>Коды отказа</th></tr></thead>
|
||||
<tbody>
|
||||
{{range .Claim.M2MDecision.Securities}}
|
||||
<tr>
|
||||
<td><code>{{.ReferenceID}}</code></td>
|
||||
<td><span class="badge {{if eq .Outcome "confirmed"}}confirmed{{else}}rejected{{end}}">{{.Outcome}}</span></td>
|
||||
<td>{{range .RejectCodes}}<code>{{.}}</code> {{end}}</td>
|
||||
</tr>
|
||||
{{end}}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
{{end}}
|
||||
|
||||
{{if .Claim.LastCallback}}
|
||||
<div class="card">
|
||||
<h2>Последний callback в ЛК</h2>
|
||||
<table>
|
||||
<tr><td style="width:160px" class="muted">Статус</td><td><span class="badge {{.Claim.LastCallback.NewStatus}}">{{.Claim.LastCallback.NewStatus}}</span></td></tr>
|
||||
{{if .Claim.LastCallback.ReasonCode}}
|
||||
<tr><td class="muted">Код причины</td><td><code>{{.Claim.LastCallback.ReasonCode}}</code> {{.Claim.LastCallback.ReasonText}}</td></tr>
|
||||
{{end}}
|
||||
<tr><td class="muted">Время</td><td>{{.Claim.LastCallback.UpdatedAt.Format "02.01.2006 15:04:05"}}</td></tr>
|
||||
</table>
|
||||
</div>
|
||||
{{end}}
|
||||
{{end}}
|
||||
@@ -0,0 +1,27 @@
|
||||
{{define "content"}}
|
||||
<div class="card">
|
||||
<h2>Журнал заявок ({{len .Items}})</h2>
|
||||
{{if .Items}}
|
||||
<table>
|
||||
<thead><tr><th>Создана</th><th>ID</th><th>GUID M2M</th><th>Инвестор</th><th>ЦБ</th><th>Передающий</th><th>Принимающий</th><th>Статус</th><th></th></tr></thead>
|
||||
<tbody>
|
||||
{{range .Items}}
|
||||
<tr>
|
||||
<td>{{.CreatedAt.Format "02.01 15:04:05"}}</td>
|
||||
<td><code>{{slice .ID 0 8}}</code></td>
|
||||
<td><code>{{slice (printf "%s" .M2MGUID) 0 8}}</code></td>
|
||||
<td>{{.Investor.LastName}} {{slice .Investor.FirstName 0 1}}.</td>
|
||||
<td>{{len .Securities}}</td>
|
||||
<td><code>{{.TransferringDepositoryINN}}</code></td>
|
||||
<td><code>{{.ReceivingDepositoryINN}}</code></td>
|
||||
<td><span class="badge {{.Status}}">{{.Status}}</span></td>
|
||||
<td><a href="/admin/claims/{{.ID}}">детали →</a></td>
|
||||
</tr>
|
||||
{{end}}
|
||||
</tbody>
|
||||
</table>
|
||||
{{else}}
|
||||
<p class="muted">Пусто.</p>
|
||||
{{end}}
|
||||
</div>
|
||||
{{end}}
|
||||
@@ -0,0 +1,57 @@
|
||||
{{define "content"}}
|
||||
<div class="grid">
|
||||
<div class="stat">
|
||||
<div class="stat-label">Всего сделок</div>
|
||||
<div class="stat-value">{{.Counts.Total}}</div>
|
||||
</div>
|
||||
<div class="stat">
|
||||
<div class="stat-label">Подтверждено</div>
|
||||
<div class="stat-value" style="color: var(--ok)">{{.Counts.Confirmed}}</div>
|
||||
</div>
|
||||
<div class="stat">
|
||||
<div class="stat-label">В ожидании</div>
|
||||
<div class="stat-value" style="color: var(--warn)">{{.Counts.InProgress}}</div>
|
||||
</div>
|
||||
<div class="stat">
|
||||
<div class="stat-label">Отказы / таймауты</div>
|
||||
<div class="stat-value" style="color: var(--err)">{{.Counts.Failed}}</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="card">
|
||||
<h2>Состояние системы</h2>
|
||||
{{range .Status.Checks}}
|
||||
<div style="padding: 6px 0">
|
||||
<span class="dot {{if .OK}}ok{{else}}err{{end}}"></span>
|
||||
<strong>{{.Name}}</strong> — {{.Message}}
|
||||
{{if .Detail}}<span class="muted"> · <code>{{.Detail}}</code></span>{{end}}
|
||||
</div>
|
||||
{{end}}
|
||||
<div class="muted" style="margin-top: 12px">
|
||||
Профиль: <code>{{.Status.Profile}}</code> · Crypto-провайдер: <code>{{.Status.Provider}}</code>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="card">
|
||||
<h2>Последние заявки</h2>
|
||||
{{if .Recent}}
|
||||
<table>
|
||||
<thead><tr><th>Создана</th><th>ID</th><th>Инвестор</th><th>ЦБ</th><th>Статус</th><th></th></tr></thead>
|
||||
<tbody>
|
||||
{{range .Recent}}
|
||||
<tr>
|
||||
<td>{{.CreatedAt.Format "15:04:05"}}</td>
|
||||
<td><code>{{slice .ID 0 8}}</code></td>
|
||||
<td>{{.Investor.LastName}} {{slice .Investor.FirstName 0 1}}.</td>
|
||||
<td>{{len .Securities}}</td>
|
||||
<td><span class="badge {{.Status}}">{{.Status}}</span></td>
|
||||
<td><a href="/admin/claims/{{.ID}}">открыть →</a></td>
|
||||
</tr>
|
||||
{{end}}
|
||||
</tbody>
|
||||
</table>
|
||||
{{else}}
|
||||
<p class="muted">Заявок ещё нет. Подайте первую через lk-emulator или POST /api/v1/back_office/claims/.</p>
|
||||
{{end}}
|
||||
</div>
|
||||
{{end}}
|
||||
@@ -0,0 +1,30 @@
|
||||
{{define "content"}}
|
||||
<div class="card">
|
||||
<h2>Статус системы — детально</h2>
|
||||
<table>
|
||||
<thead><tr><th></th><th>Подсистема</th><th>Состояние</th><th>Сообщение</th><th>Детали</th></tr></thead>
|
||||
<tbody>
|
||||
{{range .Checks}}
|
||||
<tr>
|
||||
<td><span class="dot {{if .OK}}ok{{else}}err{{end}}"></span></td>
|
||||
<td><strong>{{.Name}}</strong></td>
|
||||
<td>{{if .OK}}<span style="color: var(--ok)">OK</span>{{else}}<span style="color: var(--err)">FAIL</span>{{end}}</td>
|
||||
<td>{{.Message}}</td>
|
||||
<td><code>{{.Detail}}</code></td>
|
||||
</tr>
|
||||
{{end}}
|
||||
</tbody>
|
||||
</table>
|
||||
<p class="muted" style="margin-top: 16px">Проверка выполнена в {{.CheckedAt.Format "15:04:05 02.01.2006"}}.</p>
|
||||
</div>
|
||||
|
||||
<div class="card">
|
||||
<h2>Что подключается на следующих этапах</h2>
|
||||
<table>
|
||||
<tr><td class="muted" style="width:240px">PostgreSQL (схема m2m_core)</td><td>M2-шаг-3: pgx-репозиторий вместо MemoryRepository. Миграция готова — <code>migrations/m2m-core/001__deals.sql</code>.</td></tr>
|
||||
<tr><td class="muted">crypto-service · КриптоПро JCP</td><td>M4: положить <code>jcp.jar</code> в <code>services/crypto-service/libs/</code>, выставить <code>BJ_CRYPTO_PROVIDER=cryptopro</code>, заполнить keystore профиля. Проверка — gRPC Health должна вернуть <code>provider=cryptopro, ok=true</code>.</td></tr>
|
||||
<tr><td class="muted">nsd-adapter · ИШ НРД</td><td>M3: установить ИШ, выставить <code>BJ_NSD_PROFILE=guest-gost</code> или иной, <code>BJ_NSD_IGW_URL=http://localhost:8080</code>. Без этого сейчас используется <code>nsdadapter/mock</code> с эмуляцией ответов через 3 сек.</td></tr>
|
||||
<tr><td class="muted">Реальный ЛК (ESIA Finance)</td><td>M4: согласовать <code>docs/lk-contract/v1/openapi.yaml</code> с командой ЛК, выставить <code>BJ_LK_CALLBACK_URL</code> на реальный адрес. Сейчас callback идёт в встроенный lk-emulator.</td></tr>
|
||||
</table>
|
||||
</div>
|
||||
{{end}}
|
||||
@@ -0,0 +1,58 @@
|
||||
{{define "layout"}}<!DOCTYPE html>
|
||||
<html lang="ru">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<title>{{.Title}} · lk-gateway</title>
|
||||
<style>
|
||||
:root { --bg:#0f1115; --card:#1a1d24; --border:#2a2f3a; --text:#e8eaed; --muted:#8b94a3; --accent:#5b9dff; --ok:#3fbf6c; --warn:#e8b13a; --err:#e85a5a; }
|
||||
* { box-sizing: border-box; }
|
||||
body { margin:0; font-family: system-ui, -apple-system, sans-serif; background: var(--bg); color: var(--text); }
|
||||
header { padding: 16px 24px; border-bottom: 1px solid var(--border); display: flex; align-items: center; gap: 24px; }
|
||||
header h1 { margin: 0; font-size: 18px; font-weight: 600; }
|
||||
header nav a { color: var(--muted); text-decoration: none; margin-right: 16px; font-size: 14px; }
|
||||
header nav a:hover, header nav a.active { color: var(--text); }
|
||||
main { padding: 24px; max-width: 1280px; margin: 0 auto; }
|
||||
h2 { font-size: 16px; margin: 0 0 12px; font-weight: 600; }
|
||||
.card { background: var(--card); border: 1px solid var(--border); border-radius: 6px; padding: 16px; margin-bottom: 16px; }
|
||||
.grid { display: grid; gap: 12px; grid-template-columns: repeat(auto-fit, minmax(220px, 1fr)); }
|
||||
.stat { padding: 12px; background: var(--card); border: 1px solid var(--border); border-radius: 6px; }
|
||||
.stat-label { font-size: 12px; color: var(--muted); text-transform: uppercase; letter-spacing: .04em; }
|
||||
.stat-value { font-size: 22px; font-weight: 600; margin-top: 4px; }
|
||||
.dot { display: inline-block; width: 8px; height: 8px; border-radius: 50%; margin-right: 6px; }
|
||||
.dot.ok { background: var(--ok); }
|
||||
.dot.warn { background: var(--warn); }
|
||||
.dot.err { background: var(--err); }
|
||||
table { width: 100%; border-collapse: collapse; font-size: 14px; }
|
||||
th, td { text-align: left; padding: 8px 12px; border-bottom: 1px solid var(--border); }
|
||||
th { color: var(--muted); font-weight: 500; font-size: 12px; text-transform: uppercase; letter-spacing: .04em; }
|
||||
tr:hover td { background: rgba(91,157,255,0.05); }
|
||||
a { color: var(--accent); }
|
||||
.badge { display: inline-block; padding: 2px 8px; border-radius: 4px; font-size: 11px; font-weight: 600; }
|
||||
.badge.draft, .badge.validated, .badge.submitted_to_nsd { background: rgba(91,157,255,0.15); color: #5b9dff; }
|
||||
.badge.awaiting_decision { background: rgba(232,177,58,0.15); color: var(--warn); }
|
||||
.badge.confirmed, .badge.awaiting_sub16, .badge.done { background: rgba(63,191,108,0.15); color: var(--ok); }
|
||||
.badge.rejected, .badge.timed_out { background: rgba(232,90,90,0.15); color: var(--err); }
|
||||
.badge.manual_approval { background: rgba(232,177,58,0.15); color: var(--warn); }
|
||||
code { background: var(--border); padding: 2px 6px; border-radius: 3px; font-size: 12px; }
|
||||
.muted { color: var(--muted); font-size: 13px; }
|
||||
pre { background: #0a0c10; border: 1px solid var(--border); border-radius: 4px; padding: 12px; font-size: 12px; overflow: auto; max-height: 400px; }
|
||||
button, .btn { background: var(--accent); color: white; border: none; padding: 8px 16px; border-radius: 4px; cursor: pointer; font-size: 14px; }
|
||||
button:hover, .btn:hover { opacity: .9; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<header>
|
||||
<h1>lk-gateway</h1>
|
||||
<nav>
|
||||
<a href="/admin/" class="{{if eq .Active "home"}}active{{end}}">Дашборд</a>
|
||||
<a href="/admin/claims" class="{{if eq .Active "claims"}}active{{end}}">Заявки</a>
|
||||
<a href="/admin/status" class="{{if eq .Active "status"}}active{{end}}">Статус системы</a>
|
||||
</nav>
|
||||
<span class="muted" style="margin-left:auto">{{.Now}}</span>
|
||||
</header>
|
||||
<main>
|
||||
{{template "content" .}}
|
||||
</main>
|
||||
</body>
|
||||
</html>
|
||||
{{end}}
|
||||
Reference in New Issue
Block a user