ok
This commit is contained in:
@@ -18,9 +18,9 @@ export const config = {
|
|||||||
corsOrigin: process.env.CORS_ORIGIN || '*',
|
corsOrigin: process.env.CORS_ORIGIN || '*',
|
||||||
|
|
||||||
trueApi: {
|
trueApi: {
|
||||||
authPath: '/auth',
|
authPath: 'auth',
|
||||||
cisesInfoPath: '/cises/info',
|
cisesInfoPath: 'cises/info',
|
||||||
codesCheckPath: '/codes/check',
|
codesCheckPath: 'codes/check',
|
||||||
batchSize: 1000,
|
batchSize: 1000,
|
||||||
tokenTTL: 10 * 60 * 60 * 1000,
|
tokenTTL: 10 * 60 * 60 * 1000,
|
||||||
maxRetries: 3,
|
maxRetries: 3,
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
import type { FastifyInstance } from 'fastify'
|
import type { FastifyInstance } from 'fastify'
|
||||||
import type { TrueApiEnv } from '../config.js'
|
import type { TrueApiEnv } from '../config.js'
|
||||||
import { getAuthKey, signIn, clearToken, getAuthStatus } from '../services/auth-service.js'
|
import { getAuthKey, signIn, clearToken, getAuthStatus, setTokenDirect } from '../services/auth-service.js'
|
||||||
import { AppError, extractDebugInfo } from '../services/cises-service.js'
|
import { AppError, extractDebugInfo } from '../services/cises-service.js'
|
||||||
|
|
||||||
const VALID_ENVS = ['sandbox', 'prod']
|
const VALID_ENVS = ['sandbox', 'prod']
|
||||||
@@ -18,6 +18,7 @@ const signInSchema = {
|
|||||||
properties: {
|
properties: {
|
||||||
uuid: { type: 'string' },
|
uuid: { type: 'string' },
|
||||||
data: { type: 'string' },
|
data: { type: 'string' },
|
||||||
|
inn: { type: 'string' },
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
@@ -43,11 +44,12 @@ export async function authRoutes(app: FastifyInstance): Promise<void> {
|
|||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
app.post<{ Body: { uuid: string; data: string } }>('/auth/simpleSignIn', { schema: signInSchema }, async (request, reply) => {
|
app.post<{ Body: { uuid: string; data: string; inn?: string } }>('/auth/simpleSignIn', { schema: signInSchema }, async (request, reply) => {
|
||||||
const env = parseEnv(request.query as Record<string, string>)
|
const env = parseEnv(request.query as Record<string, string>)
|
||||||
try {
|
try {
|
||||||
const { uuid, data } = request.body
|
const { uuid, data, inn } = request.body
|
||||||
const result = await signIn(env, { uuid, data })
|
const result = await signIn(env, { uuid, data, inn })
|
||||||
|
request.log.info({ env, token: result.token }, 'auth: token received')
|
||||||
return result
|
return result
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
if (err instanceof AppError) {
|
if (err instanceof AppError) {
|
||||||
@@ -74,4 +76,11 @@ export async function authRoutes(app: FastifyInstance): Promise<void> {
|
|||||||
clearToken(env)
|
clearToken(env)
|
||||||
return { success: true }
|
return { success: true }
|
||||||
})
|
})
|
||||||
|
|
||||||
|
app.post<{ Body: { token: string } }>('/auth/setToken', async (request) => {
|
||||||
|
const env = parseEnv(request.query as Record<string, string>)
|
||||||
|
setTokenDirect(env, request.body.token)
|
||||||
|
request.log.info({ env, tokenPrefix: request.body.token.slice(0, 20) + '...' }, 'auth: token set manually')
|
||||||
|
return { success: true }
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -35,7 +35,7 @@ export async function cisesRoutes(app: FastifyInstance): Promise<void> {
|
|||||||
app.post<{ Body: CheckCodesRequest }>('/api/check-codes/auth', { schema: checkCodesSchema }, async (request, reply) => {
|
app.post<{ Body: CheckCodesRequest }>('/api/check-codes/auth', { schema: checkCodesSchema }, async (request, reply) => {
|
||||||
const env = parseEnv(request.query as Record<string, string>)
|
const env = parseEnv(request.query as Record<string, string>)
|
||||||
try {
|
try {
|
||||||
return await checkCodesAuth(env, request.body)
|
return await checkCodesAuth(env, request.body, (msg, data) => request.log.error(data, msg))
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
if (err instanceof AppError) {
|
if (err instanceof AppError) {
|
||||||
return reply.status(err.statusCode).send({
|
return reply.status(err.statusCode).send({
|
||||||
|
|||||||
@@ -1,17 +1,50 @@
|
|||||||
import got from 'got'
|
import got from 'got'
|
||||||
|
import type { Response } from 'got'
|
||||||
import { config, envUrls } from '../config.js'
|
import { config, envUrls } from '../config.js'
|
||||||
import type { TrueApiEnv } from '../config.js'
|
import type { TrueApiEnv } from '../config.js'
|
||||||
import { getToken, setToken, invalidateToken, hasToken, getTokenTTL } from './token-cache.js'
|
import { getToken, setToken, invalidateToken, hasToken, getTokenTTL } from './token-cache.js'
|
||||||
import { AppError, extractDebugInfo } from './cises-service.js'
|
import { AppError, extractDebugInfo } from './cises-service.js'
|
||||||
import type { AuthKeyResponse, AuthSignInRequest, AuthSignInResponse } from '../types/index.js'
|
import type { AuthKeyResponse, AuthSignInRequest, AuthSignInResponse } from '../types/index.js'
|
||||||
|
|
||||||
function authClient(env: TrueApiEnv) {
|
function loggedClient(prefixUrl: string) {
|
||||||
return got.extend({
|
return got.extend({
|
||||||
prefixUrl: envUrls[env].baseUrl + config.trueApi.authPath,
|
prefixUrl,
|
||||||
responseType: 'json',
|
responseType: 'json',
|
||||||
|
hooks: {
|
||||||
|
beforeRequest: [
|
||||||
|
(options) => {
|
||||||
|
const headers = { ...options.headers } as Record<string, string>
|
||||||
|
if (headers.authorization) {
|
||||||
|
headers.authorization = 'Bearer ***'
|
||||||
|
}
|
||||||
|
console.log(JSON.stringify({
|
||||||
|
type: 'trueapi_request',
|
||||||
|
method: options.method,
|
||||||
|
url: String(options.url || ''),
|
||||||
|
headers,
|
||||||
|
body: options.json || options.body || null,
|
||||||
|
}))
|
||||||
|
},
|
||||||
|
],
|
||||||
|
afterResponse: [
|
||||||
|
(response: Response) => {
|
||||||
|
console.log(JSON.stringify({
|
||||||
|
type: 'trueapi_response',
|
||||||
|
statusCode: response.statusCode,
|
||||||
|
url: response.requestUrl,
|
||||||
|
body: response.body,
|
||||||
|
}))
|
||||||
|
return response
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function authClient(env: TrueApiEnv) {
|
||||||
|
return loggedClient(envUrls[env].baseUrl + config.trueApi.authPath)
|
||||||
|
}
|
||||||
|
|
||||||
export async function getAuthKey(env: TrueApiEnv): Promise<AuthKeyResponse> {
|
export async function getAuthKey(env: TrueApiEnv): Promise<AuthKeyResponse> {
|
||||||
try {
|
try {
|
||||||
const { body } = await authClient(env).get<AuthKeyResponse>('key')
|
const { body } = await authClient(env).get<AuthKeyResponse>('key')
|
||||||
@@ -25,8 +58,12 @@ export async function getAuthKey(env: TrueApiEnv): Promise<AuthKeyResponse> {
|
|||||||
|
|
||||||
export async function signIn(env: TrueApiEnv, body: AuthSignInRequest): Promise<AuthSignInResponse> {
|
export async function signIn(env: TrueApiEnv, body: AuthSignInRequest): Promise<AuthSignInResponse> {
|
||||||
try {
|
try {
|
||||||
|
const requestBody: Record<string, unknown> = { uuid: body.uuid, data: body.data }
|
||||||
|
if (body.inn) {
|
||||||
|
requestBody.inn = body.inn
|
||||||
|
}
|
||||||
const { body: response } = await authClient(env).post<AuthSignInResponse>('simpleSignIn', {
|
const { body: response } = await authClient(env).post<AuthSignInResponse>('simpleSignIn', {
|
||||||
json: body,
|
json: requestBody,
|
||||||
})
|
})
|
||||||
setToken(env, response.token)
|
setToken(env, response.token)
|
||||||
return response
|
return response
|
||||||
@@ -41,6 +78,10 @@ export function getCachedToken(env: TrueApiEnv): string | undefined {
|
|||||||
return getToken(env)
|
return getToken(env)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export function setTokenDirect(env: TrueApiEnv, token: string): void {
|
||||||
|
setToken(env, token)
|
||||||
|
}
|
||||||
|
|
||||||
export function clearToken(env: TrueApiEnv): void {
|
export function clearToken(env: TrueApiEnv): void {
|
||||||
invalidateToken(env)
|
invalidateToken(env)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,22 +1,56 @@
|
|||||||
import got from 'got'
|
import got from 'got'
|
||||||
|
import type { Response } from 'got'
|
||||||
import { config, envUrls } from '../config.js'
|
import { config, envUrls } from '../config.js'
|
||||||
import type { TrueApiEnv } from '../config.js'
|
import type { TrueApiEnv } from '../config.js'
|
||||||
import { getCachedToken, clearToken } from './auth-service.js'
|
import { getCachedToken, clearToken } from './auth-service.js'
|
||||||
import type {
|
import type {
|
||||||
CisInfoResponse,
|
CisInfoResponseItem,
|
||||||
PublicCheckResponse,
|
PublicCheckResponse,
|
||||||
CheckCodesRequest,
|
CheckCodesRequest,
|
||||||
CheckCodesResponse,
|
CheckCodesResponse,
|
||||||
SingleCodeResult,
|
SingleCodeResult,
|
||||||
|
ApiDebugInfo,
|
||||||
} from '../types/index.js'
|
} from '../types/index.js'
|
||||||
|
|
||||||
function apiClient(env: TrueApiEnv) {
|
function loggedClient(prefixUrl: string) {
|
||||||
return got.extend({
|
return got.extend({
|
||||||
prefixUrl: envUrls[env].baseUrl,
|
prefixUrl,
|
||||||
responseType: 'json',
|
responseType: 'json',
|
||||||
|
hooks: {
|
||||||
|
beforeRequest: [
|
||||||
|
(options) => {
|
||||||
|
const headers = { ...options.headers } as Record<string, string>
|
||||||
|
if (headers.authorization) {
|
||||||
|
headers.authorization = 'Bearer ***'
|
||||||
|
}
|
||||||
|
console.log(JSON.stringify({
|
||||||
|
type: 'trueapi_request',
|
||||||
|
method: options.method,
|
||||||
|
url: String(options.url || ''),
|
||||||
|
headers,
|
||||||
|
body: options.json || options.body || null,
|
||||||
|
}))
|
||||||
|
},
|
||||||
|
],
|
||||||
|
afterResponse: [
|
||||||
|
(response: Response) => {
|
||||||
|
console.log(JSON.stringify({
|
||||||
|
type: 'trueapi_response',
|
||||||
|
statusCode: response.statusCode,
|
||||||
|
url: response.requestUrl,
|
||||||
|
body: response.body,
|
||||||
|
}))
|
||||||
|
return response
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function apiClient(env: TrueApiEnv) {
|
||||||
|
return loggedClient(envUrls[env].baseUrl)
|
||||||
|
}
|
||||||
|
|
||||||
export async function checkCodesPublic(env: TrueApiEnv, body: CheckCodesRequest): Promise<CheckCodesResponse> {
|
export async function checkCodesPublic(env: TrueApiEnv, body: CheckCodesRequest): Promise<CheckCodesResponse> {
|
||||||
const results: SingleCodeResult[] = []
|
const results: SingleCodeResult[] = []
|
||||||
const queue = [...body.codes]
|
const queue = [...body.codes]
|
||||||
@@ -25,9 +59,9 @@ export async function checkCodesPublic(env: TrueApiEnv, body: CheckCodesRequest)
|
|||||||
while (queue.length > 0) {
|
while (queue.length > 0) {
|
||||||
const code = queue.shift()!
|
const code = queue.shift()!
|
||||||
try {
|
try {
|
||||||
const { body: response } = await got.get<PublicCheckResponse>(
|
const { body: response } = await loggedClient(envUrls[env].publicCheckUrl).get<PublicCheckResponse>(
|
||||||
`${envUrls[env].publicCheckUrl}?code=${encodeURIComponent(code)}`,
|
`?code=${encodeURIComponent(code)}`,
|
||||||
{ responseType: 'json', timeout: { request: 10000 } }
|
{ timeout: { request: 10000 } }
|
||||||
)
|
)
|
||||||
results.push({
|
results.push({
|
||||||
code: response.code,
|
code: response.code,
|
||||||
@@ -59,9 +93,14 @@ function getToken(env: TrueApiEnv): string {
|
|||||||
return token
|
return token
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function checkCodesAuth(env: TrueApiEnv, body: CheckCodesRequest): Promise<CheckCodesResponse> {
|
export async function checkCodesAuth(
|
||||||
|
env: TrueApiEnv,
|
||||||
|
body: CheckCodesRequest,
|
||||||
|
log?: (msg: string, data?: Record<string, unknown>) => void,
|
||||||
|
): Promise<CheckCodesResponse> {
|
||||||
const token = getToken(env)
|
const token = getToken(env)
|
||||||
const results: SingleCodeResult[] = []
|
const results: SingleCodeResult[] = []
|
||||||
|
let debugInfo: ApiDebugInfo | undefined
|
||||||
|
|
||||||
try {
|
try {
|
||||||
await processBatch(env, body.codes, token, results, 0)
|
await processBatch(env, body.codes, token, results, 0)
|
||||||
@@ -70,6 +109,14 @@ export async function checkCodesAuth(env: TrueApiEnv, body: CheckCodesRequest):
|
|||||||
clearToken(env)
|
clearToken(env)
|
||||||
throw err
|
throw err
|
||||||
}
|
}
|
||||||
|
if (err instanceof AppError) {
|
||||||
|
debugInfo = err.debugInfo
|
||||||
|
if (log) log('Auth API error (non-401)', { error: err.message, debugInfo })
|
||||||
|
} else {
|
||||||
|
debugInfo = extractDebugInfo(err)
|
||||||
|
if (log) log('Auth API error (non-401)', { error: String(err), debugInfo })
|
||||||
|
}
|
||||||
|
|
||||||
for (const code of body.codes) {
|
for (const code of body.codes) {
|
||||||
if (!results.find(r => r.code === code)) {
|
if (!results.find(r => r.code === code)) {
|
||||||
results.push({ code, found: false, valid: false, status: 'ERROR', error: 'Auth API error' })
|
results.push({ code, found: false, valid: false, status: 'ERROR', error: 'Auth API error' })
|
||||||
@@ -77,20 +124,46 @@ export async function checkCodesAuth(env: TrueApiEnv, body: CheckCodesRequest):
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return buildResponse(results)
|
return buildResponse(results, debugInfo)
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface ApiDebugInfo {
|
function buildResponse(results: SingleCodeResult[], debugInfo?: ApiDebugInfo): CheckCodesResponse {
|
||||||
request: {
|
return {
|
||||||
method: string
|
results,
|
||||||
url: string
|
total: results.length,
|
||||||
headers: Record<string, string>
|
validCount: results.filter(r => r.valid).length,
|
||||||
body: unknown
|
invalidCount: results.filter(r => !r.valid && !r.error).length,
|
||||||
|
errorCount: results.filter(r => !!r.error).length,
|
||||||
|
debugInfo,
|
||||||
}
|
}
|
||||||
response: {
|
}
|
||||||
statusCode: number
|
|
||||||
headers: Record<string, string>
|
function extractRequestHeaders(options: Record<string, unknown> | undefined): Record<string, string> {
|
||||||
body: unknown
|
const reqHeaders = options?.headers as Record<string, string> | undefined
|
||||||
|
const clean: Record<string, string> = {}
|
||||||
|
if (reqHeaders) {
|
||||||
|
for (const [k, v] of Object.entries(reqHeaders)) {
|
||||||
|
clean[k] = k.toLowerCase() === 'authorization' ? 'Bearer ***' : String(v)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return clean
|
||||||
|
}
|
||||||
|
|
||||||
|
export function extractDebugInfoFromResponse<T>(response: Response<T>): ApiDebugInfo {
|
||||||
|
const req = response.request as unknown as Record<string, unknown> | undefined
|
||||||
|
const opts = req?.options as Record<string, unknown> | undefined
|
||||||
|
return {
|
||||||
|
request: {
|
||||||
|
method: String(opts?.method || 'POST'),
|
||||||
|
url: String(response.requestUrl || response.url || 'unknown'),
|
||||||
|
headers: extractRequestHeaders(opts),
|
||||||
|
body: (opts?.json || opts?.body) ?? null,
|
||||||
|
},
|
||||||
|
response: {
|
||||||
|
statusCode: response.statusCode,
|
||||||
|
headers: (response.headers || {}) as Record<string, string>,
|
||||||
|
body: response.body ?? null,
|
||||||
|
},
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -99,33 +172,37 @@ export function extractDebugInfo(err: unknown): ApiDebugInfo | undefined {
|
|||||||
const gotErr = err as Record<string, unknown>
|
const gotErr = err as Record<string, unknown>
|
||||||
const response = gotErr.response as Record<string, unknown> | undefined
|
const response = gotErr.response as Record<string, unknown> | undefined
|
||||||
const options = gotErr.options as Record<string, unknown> | undefined
|
const options = gotErr.options as Record<string, unknown> | undefined
|
||||||
if (!response) return undefined
|
|
||||||
|
|
||||||
const reqHeaders = options?.headers as Record<string, string> | undefined
|
const code = gotErr.code ? String(gotErr.code) : undefined
|
||||||
const cleanHeaders: Record<string, string> = {}
|
const message = gotErr.message ? String(gotErr.message) : undefined
|
||||||
if (reqHeaders) {
|
|
||||||
for (const [k, v] of Object.entries(reqHeaders)) {
|
const cleanHeaders = extractRequestHeaders(options)
|
||||||
if (k.toLowerCase() === 'authorization') {
|
|
||||||
cleanHeaders[k] = 'Bearer ***'
|
let reqUrl = 'unknown'
|
||||||
} else {
|
if (response?.requestUrl) {
|
||||||
cleanHeaders[k] = String(v)
|
reqUrl = String(response.requestUrl)
|
||||||
}
|
} else if (options) {
|
||||||
}
|
const u = (options as Record<string, unknown>).url
|
||||||
|
if (u) reqUrl = String(u)
|
||||||
|
else if ((options as Record<string, unknown>).href) reqUrl = String((options as Record<string, unknown>).href)
|
||||||
|
else if ((options as Record<string, unknown>).pathname) reqUrl = String((options as Record<string, unknown>).pathname)
|
||||||
}
|
}
|
||||||
|
|
||||||
const resHeaders = response.headers as Record<string, string> | undefined
|
const resHeaders = response?.headers as Record<string, string> | undefined
|
||||||
|
|
||||||
return {
|
return {
|
||||||
request: {
|
request: {
|
||||||
method: String(options?.method || 'POST'),
|
method: String(options?.method || 'POST'),
|
||||||
url: String(response.requestUrl || (options?.url?.toString()) || 'unknown'),
|
url: reqUrl,
|
||||||
headers: cleanHeaders,
|
headers: cleanHeaders,
|
||||||
body: options?.json || options?.body || null,
|
body: options?.json || options?.body || null,
|
||||||
},
|
},
|
||||||
response: {
|
response: {
|
||||||
statusCode: Number(response.statusCode),
|
statusCode: Number(response?.statusCode || 0),
|
||||||
headers: resHeaders || {},
|
headers: resHeaders || {},
|
||||||
body: response.body || null,
|
body: response?.body || null,
|
||||||
|
errorCode: code,
|
||||||
|
errorMessage: message,
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -147,56 +224,49 @@ async function processBatch(
|
|||||||
async function retryOnError(
|
async function retryOnError(
|
||||||
env: TrueApiEnv, batch: string[], token: string, results: SingleCodeResult[], attempt = 0
|
env: TrueApiEnv, batch: string[], token: string, results: SingleCodeResult[], attempt = 0
|
||||||
): Promise<void> {
|
): Promise<void> {
|
||||||
try {
|
const response = await apiClient(env).post<CisInfoResponseItem[]>(
|
||||||
const { body: response } = await apiClient(env).post<CisInfoResponse>(
|
config.trueApi.cisesInfoPath,
|
||||||
config.trueApi.cisesInfoPath,
|
{
|
||||||
{
|
json: batch,
|
||||||
json: { cisList: batch },
|
headers: { Authorization: `Bearer ${token}` },
|
||||||
headers: { Authorization: `Bearer ${token}` },
|
timeout: { request: 30000 },
|
||||||
timeout: { request: 30000 },
|
throwHttpErrors: false,
|
||||||
}
|
|
||||||
)
|
|
||||||
|
|
||||||
for (const item of response.cisInfo) {
|
|
||||||
results.push({
|
|
||||||
code: item.requestedCis,
|
|
||||||
found: !!item.cis,
|
|
||||||
valid: item.status === 'INTRODUCED' || item.status === 'APPLIED' || item.status === 'EMITTED',
|
|
||||||
status: item.status || 'UNKNOWN',
|
|
||||||
gtin: item.gtin,
|
|
||||||
productName: item.productName,
|
|
||||||
producerName: item.producerName,
|
|
||||||
ownerName: item.ownerName,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
} catch (err) {
|
|
||||||
if (is401(err)) {
|
|
||||||
const debugInfo = extractDebugInfo(err)
|
|
||||||
throw new AppError('Token expired', 401, debugInfo)
|
|
||||||
}
|
}
|
||||||
|
)
|
||||||
|
|
||||||
const isRetryable = isRetryableError(err)
|
if (response.statusCode === 401) {
|
||||||
if (isRetryable && attempt < config.trueApi.maxRetries) {
|
const debugInfo = extractDebugInfoFromResponse(response)
|
||||||
const delay = Math.pow(2, attempt) * 500
|
throw new AppError('Token expired', 401, debugInfo)
|
||||||
await sleep(delay)
|
|
||||||
return retryOnError(env, batch, token, results, attempt + 1)
|
|
||||||
}
|
|
||||||
|
|
||||||
throw err
|
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
function is401(err: unknown): boolean {
|
if (response.statusCode === 429 || (response.statusCode >= 500 && attempt < config.trueApi.maxRetries)) {
|
||||||
if (!err || typeof err !== 'object') return false
|
const delay = Math.pow(2, attempt) * 500
|
||||||
return 'response' in err &&
|
await sleep(delay)
|
||||||
(err as { response?: { statusCode?: number } }).response?.statusCode === 401
|
return retryOnError(env, batch, token, results, attempt + 1)
|
||||||
}
|
}
|
||||||
|
|
||||||
function isRetryableError(err: unknown): boolean {
|
if (!response.body || !Array.isArray(response.body)) {
|
||||||
if (!err || typeof err !== 'object') return true
|
const debugInfo = extractDebugInfoFromResponse(response)
|
||||||
const statusCode = (err as { response?: { statusCode?: number } }).response?.statusCode
|
const apiErr = response.body && typeof response.body === 'object'
|
||||||
if (!statusCode) return true
|
? (response.body as Record<string, unknown>).error_message || ''
|
||||||
return statusCode === 429 || statusCode >= 500
|
: ''
|
||||||
|
throw new AppError(`API error: ${apiErr || response.statusCode}`, response.statusCode, debugInfo)
|
||||||
|
}
|
||||||
|
|
||||||
|
const items = response.body as CisInfoResponseItem[]
|
||||||
|
for (const item of items) {
|
||||||
|
const ci = item.cisInfo
|
||||||
|
results.push({
|
||||||
|
code: ci.requestedCis,
|
||||||
|
found: !!ci.cis && !item.errorCode,
|
||||||
|
valid: ci.status === 'INTRODUCED' || ci.status === 'APPLIED' || ci.status === 'EMITTED',
|
||||||
|
status: item.errorCode || ci.status || 'UNKNOWN',
|
||||||
|
gtin: ci.gtin,
|
||||||
|
productName: ci.productName,
|
||||||
|
producerName: ci.producerName,
|
||||||
|
ownerName: ci.ownerName,
|
||||||
|
})
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function sleep(ms: number): Promise<void> {
|
function sleep(ms: number): Promise<void> {
|
||||||
@@ -213,12 +283,4 @@ export class AppError extends Error {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function buildResponse(results: SingleCodeResult[]): CheckCodesResponse {
|
|
||||||
return {
|
|
||||||
results,
|
|
||||||
total: results.length,
|
|
||||||
validCount: results.filter(r => r.valid).length,
|
|
||||||
invalidCount: results.filter(r => !r.valid && !r.error).length,
|
|
||||||
errorCount: results.filter(r => !!r.error).length,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ export interface AuthKeyResponse {
|
|||||||
export interface AuthSignInRequest {
|
export interface AuthSignInRequest {
|
||||||
uuid: string
|
uuid: string
|
||||||
data: string
|
data: string
|
||||||
|
inn?: string
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface AuthSignInResponse {
|
export interface AuthSignInResponse {
|
||||||
@@ -14,10 +15,6 @@ export interface AuthSignInResponse {
|
|||||||
expireDate?: string
|
expireDate?: string
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface CisInfoRequest {
|
|
||||||
cisList: string[]
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface CisInfoItem {
|
export interface CisInfoItem {
|
||||||
requestedCis: string
|
requestedCis: string
|
||||||
cis?: string
|
cis?: string
|
||||||
@@ -33,8 +30,10 @@ export interface CisInfoItem {
|
|||||||
error?: string
|
error?: string
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface CisInfoResponse {
|
export interface CisInfoResponseItem {
|
||||||
cisInfo: CisInfoItem[]
|
cisInfo: CisInfoItem
|
||||||
|
errorMessage?: string | null
|
||||||
|
errorCode?: string | null
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface PublicCheckResponse {
|
export interface PublicCheckResponse {
|
||||||
@@ -48,6 +47,22 @@ export interface CheckCodesRequest {
|
|||||||
codes: string[]
|
codes: string[]
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export interface ApiDebugInfo {
|
||||||
|
request: {
|
||||||
|
method: string
|
||||||
|
url: string
|
||||||
|
headers: Record<string, string>
|
||||||
|
body: unknown
|
||||||
|
}
|
||||||
|
response: {
|
||||||
|
statusCode: number
|
||||||
|
headers: Record<string, string>
|
||||||
|
body: unknown
|
||||||
|
errorCode?: string
|
||||||
|
errorMessage?: string
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
export interface SingleCodeResult {
|
export interface SingleCodeResult {
|
||||||
code: string
|
code: string
|
||||||
found: boolean
|
found: boolean
|
||||||
@@ -66,4 +81,5 @@ export interface CheckCodesResponse {
|
|||||||
validCount: number
|
validCount: number
|
||||||
invalidCount: number
|
invalidCount: number
|
||||||
errorCount: number
|
errorCount: number
|
||||||
|
debugInfo?: ApiDebugInfo
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import { useState, useEffect } from 'react'
|
import { useState, useEffect } from 'react'
|
||||||
import { getAuthStatus, getAuthKey, signIn } from '../services/api'
|
import { getAuthStatus, getAuthKey, signIn, setTokenManually } from '../services/api'
|
||||||
import type { RequestError } from '../services/api'
|
import type { RequestError } from '../services/api'
|
||||||
import { isCadesPluginAvailable, listCertificates, signWithCadesPlugin } from '../services/cadesplugin'
|
import { isCadesPluginAvailable, listCertificates, signWithCadesPlugin } from '../services/cadesplugin'
|
||||||
import type { CertInfo } from '../services/cadesplugin'
|
import type { CertInfo } from '../services/cadesplugin'
|
||||||
@@ -13,10 +13,13 @@ export function AuthPage({ onAuth }: Props) {
|
|||||||
const [hasPlugin, setHasPlugin] = useState<boolean | null>(null)
|
const [hasPlugin, setHasPlugin] = useState<boolean | null>(null)
|
||||||
const [certs, setCerts] = useState<CertInfo[]>([])
|
const [certs, setCerts] = useState<CertInfo[]>([])
|
||||||
const [selectedThumbprint, setSelectedThumbprint] = useState('')
|
const [selectedThumbprint, setSelectedThumbprint] = useState('')
|
||||||
|
const [inn, setInn] = useState('')
|
||||||
const [loading, setLoading] = useState(false)
|
const [loading, setLoading] = useState(false)
|
||||||
const [error, setError] = useState('')
|
const [error, setError] = useState('')
|
||||||
const [errorDebug, setErrorDebug] = useState<string | null>(null)
|
const [errorDebug, setErrorDebug] = useState<string | null>(null)
|
||||||
const [debugExpanded, setDebugExpanded] = useState(false)
|
const [debugExpanded, setDebugExpanded] = useState(false)
|
||||||
|
const [manualToken, setManualToken] = useState('')
|
||||||
|
const [manualLoading, setManualLoading] = useState(false)
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
getAuthStatus().then(setStatus).catch(() => {})
|
getAuthStatus().then(setStatus).catch(() => {})
|
||||||
@@ -34,6 +37,27 @@ export function AuthPage({ onAuth }: Props) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async function handleSetToken() {
|
||||||
|
setManualLoading(true)
|
||||||
|
setError('')
|
||||||
|
setErrorDebug(null)
|
||||||
|
setDebugExpanded(false)
|
||||||
|
try {
|
||||||
|
await setTokenManually(manualToken)
|
||||||
|
const s = await getAuthStatus()
|
||||||
|
setStatus(s)
|
||||||
|
if (s.authenticated) onAuth()
|
||||||
|
} catch (err) {
|
||||||
|
const re = err as RequestError
|
||||||
|
setError(re.message)
|
||||||
|
if (re.debugInfo) {
|
||||||
|
setErrorDebug(JSON.stringify(re.debugInfo, null, 2))
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
setManualLoading(false)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
async function handleSignIn() {
|
async function handleSignIn() {
|
||||||
setLoading(true)
|
setLoading(true)
|
||||||
setError('')
|
setError('')
|
||||||
@@ -42,7 +66,7 @@ export function AuthPage({ onAuth }: Props) {
|
|||||||
try {
|
try {
|
||||||
const { uuid, data } = await getAuthKey()
|
const { uuid, data } = await getAuthKey()
|
||||||
const signature = await signWithCadesPlugin(data, selectedThumbprint || undefined)
|
const signature = await signWithCadesPlugin(data, selectedThumbprint || undefined)
|
||||||
await signIn(uuid, signature)
|
await signIn(uuid, signature, inn || undefined)
|
||||||
const s = await getAuthStatus()
|
const s = await getAuthStatus()
|
||||||
setStatus(s)
|
setStatus(s)
|
||||||
if (s.authenticated) onAuth()
|
if (s.authenticated) onAuth()
|
||||||
@@ -92,6 +116,19 @@ export function AuthPage({ onAuth }: Props) {
|
|||||||
)}
|
)}
|
||||||
|
|
||||||
<div style={{ display: 'flex', flexDirection: 'column', gap: 12, maxWidth: 500 }}>
|
<div style={{ display: 'flex', flexDirection: 'column', gap: 12, maxWidth: 500 }}>
|
||||||
|
<div>
|
||||||
|
<label style={{ fontSize: 13, color: '#666', display: 'block', marginBottom: 4 }}>
|
||||||
|
ИНН организации:
|
||||||
|
</label>
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
value={inn}
|
||||||
|
onChange={e => setInn(e.target.value)}
|
||||||
|
placeholder="Введите ИНН для однозначной авторизации"
|
||||||
|
style={inputStyle}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
{hasPlugin && certs.length > 0 && (
|
{hasPlugin && certs.length > 0 && (
|
||||||
<div>
|
<div>
|
||||||
<label style={{ fontSize: 13, color: '#666', display: 'block', marginBottom: 4 }}>
|
<label style={{ fontSize: 13, color: '#666', display: 'block', marginBottom: 4 }}>
|
||||||
@@ -126,6 +163,39 @@ export function AuthPage({ onAuth }: Props) {
|
|||||||
{loading ? 'Подписание...' : 'Подписать и войти'}
|
{loading ? 'Подписание...' : 'Подписать и войти'}
|
||||||
</button>
|
</button>
|
||||||
|
|
||||||
|
<div style={{
|
||||||
|
borderTop: '1px solid #e0e0e0',
|
||||||
|
margin: '12px 0',
|
||||||
|
paddingTop: 16,
|
||||||
|
}}>
|
||||||
|
<label style={{ fontSize: 13, color: '#666', display: 'block', marginBottom: 4 }}>
|
||||||
|
Или введите готовый токен:
|
||||||
|
</label>
|
||||||
|
<textarea
|
||||||
|
value={manualToken}
|
||||||
|
onChange={e => setManualToken(e.target.value)}
|
||||||
|
placeholder="Вставьте токен доступа к True API"
|
||||||
|
rows={3}
|
||||||
|
style={{
|
||||||
|
...inputStyle,
|
||||||
|
fontFamily: 'monospace',
|
||||||
|
fontSize: 12,
|
||||||
|
resize: 'vertical',
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
<button
|
||||||
|
onClick={handleSetToken}
|
||||||
|
disabled={manualLoading || !manualToken.trim()}
|
||||||
|
style={{
|
||||||
|
...btnStyle,
|
||||||
|
background: '#1565c0',
|
||||||
|
marginTop: 8,
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{manualLoading ? 'Сохранение...' : 'Сохранить токен'}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
{error && (
|
{error && (
|
||||||
<div style={{ color: '#c62828', fontSize: 14, marginTop: 8 }}>Ошибка: {error}</div>
|
<div style={{ color: '#c62828', fontSize: 14, marginTop: 8 }}>Ошибка: {error}</div>
|
||||||
)}
|
)}
|
||||||
@@ -197,3 +267,12 @@ const selectStyle: React.CSSProperties = {
|
|||||||
width: '100%',
|
width: '100%',
|
||||||
boxSizing: 'border-box',
|
boxSizing: 'border-box',
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const inputStyle: React.CSSProperties = {
|
||||||
|
padding: 8,
|
||||||
|
border: '1px solid #ccc',
|
||||||
|
borderRadius: 4,
|
||||||
|
fontSize: 13,
|
||||||
|
width: '100%',
|
||||||
|
boxSizing: 'border-box',
|
||||||
|
}
|
||||||
|
|||||||
@@ -2,7 +2,7 @@ import { useState } from 'react'
|
|||||||
import { checkCodesPublic, checkCodesAuth } from '../services/api'
|
import { checkCodesPublic, checkCodesAuth } from '../services/api'
|
||||||
import type { RequestError } from '../services/api'
|
import type { RequestError } from '../services/api'
|
||||||
import { ResultsTable } from '../components/ResultsTable'
|
import { ResultsTable } from '../components/ResultsTable'
|
||||||
import type { CodeResult } from '../types'
|
import type { CodeResult, CheckCodesResponse } from '../types'
|
||||||
|
|
||||||
export function CheckCodesPage() {
|
export function CheckCodesPage() {
|
||||||
const [codesInput, setCodesInput] = useState('')
|
const [codesInput, setCodesInput] = useState('')
|
||||||
@@ -14,7 +14,7 @@ export function CheckCodesPage() {
|
|||||||
|
|
||||||
async function handleCheck(mode: 'public' | 'auth') {
|
async function handleCheck(mode: 'public' | 'auth') {
|
||||||
const codes = codesInput
|
const codes = codesInput
|
||||||
.split(/[\n,;]+/)
|
.split('\n')
|
||||||
.map(c => c.trim())
|
.map(c => c.trim())
|
||||||
.filter(Boolean)
|
.filter(Boolean)
|
||||||
|
|
||||||
@@ -29,8 +29,11 @@ export function CheckCodesPage() {
|
|||||||
setDebugExpanded(false)
|
setDebugExpanded(false)
|
||||||
try {
|
try {
|
||||||
const fn = mode === 'public' ? checkCodesPublic : checkCodesAuth
|
const fn = mode === 'public' ? checkCodesPublic : checkCodesAuth
|
||||||
const response = await fn(codes)
|
const response: CheckCodesResponse = await fn(codes)
|
||||||
setResults(response.results)
|
setResults(response.results)
|
||||||
|
if (response.debugInfo) {
|
||||||
|
setErrorDebug(JSON.stringify(response.debugInfo, null, 2))
|
||||||
|
}
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
const re = err as RequestError
|
const re = err as RequestError
|
||||||
setError(re.message)
|
setError(re.message)
|
||||||
@@ -47,7 +50,7 @@ export function CheckCodesPage() {
|
|||||||
<h2>Проверка кодов маркировки (КМ)</h2>
|
<h2>Проверка кодов маркировки (КМ)</h2>
|
||||||
|
|
||||||
<textarea
|
<textarea
|
||||||
placeholder="Введите коды маркировки (каждый с новой строки, через запятую или точку с запятой)"
|
placeholder="Введите коды маркировки (каждый с новой строки)"
|
||||||
value={codesInput}
|
value={codesInput}
|
||||||
onChange={e => setCodesInput(e.target.value)}
|
onChange={e => setCodesInput(e.target.value)}
|
||||||
rows={6}
|
rows={6}
|
||||||
|
|||||||
@@ -38,7 +38,7 @@ async function handleError(res: Response, env: ApiEnv): Promise<never> {
|
|||||||
async function request<T>(url: string, options?: RequestInit & { env?: ApiEnv }): Promise<T> {
|
async function request<T>(url: string, options?: RequestInit & { env?: ApiEnv }): Promise<T> {
|
||||||
const reqEnv = options?.env || currentEnv
|
const reqEnv = options?.env || currentEnv
|
||||||
const headers: Record<string, string> = {}
|
const headers: Record<string, string> = {}
|
||||||
if (!(options?.body instanceof FormData)) {
|
if (!(options?.body instanceof FormData) && options?.body) {
|
||||||
headers['Content-Type'] = 'application/json'
|
headers['Content-Type'] = 'application/json'
|
||||||
}
|
}
|
||||||
if (options?.headers) {
|
if (options?.headers) {
|
||||||
@@ -59,10 +59,10 @@ export async function getAuthKey(env?: ApiEnv): Promise<{ uuid: string; data: st
|
|||||||
return request('/auth/key', { env })
|
return request('/auth/key', { env })
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function signIn(uuid: string, data: string, env?: ApiEnv): Promise<{ token: string }> {
|
export async function signIn(uuid: string, data: string, inn?: string, env?: ApiEnv): Promise<{ token: string }> {
|
||||||
return request('/auth/simpleSignIn', {
|
return request('/auth/simpleSignIn', {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
body: JSON.stringify({ uuid, data }),
|
body: JSON.stringify({ uuid, data, inn }),
|
||||||
env,
|
env,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
@@ -97,6 +97,14 @@ export async function uploadUpd(file: File, env?: ApiEnv): Promise<UpdUploadResp
|
|||||||
return request('/api/upload-upd', { method: 'POST', body: formData, env })
|
return request('/api/upload-upd', { method: 'POST', body: formData, env })
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export async function setTokenManually(token: string, env?: ApiEnv): Promise<void> {
|
||||||
|
await request('/auth/setToken', {
|
||||||
|
method: 'POST',
|
||||||
|
body: JSON.stringify({ token }),
|
||||||
|
env,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
export async function getPlansList(): Promise<{ name: string; path: string; size: number }[]> {
|
export async function getPlansList(): Promise<{ name: string; path: string; size: number }[]> {
|
||||||
return request('/api/plans')
|
return request('/api/plans')
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -23,6 +23,7 @@ export interface CheckCodesResponse {
|
|||||||
validCount: number
|
validCount: number
|
||||||
invalidCount: number
|
invalidCount: number
|
||||||
errorCount: number
|
errorCount: number
|
||||||
|
debugInfo?: ApiDebugInfo
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface UpdDocument {
|
export interface UpdDocument {
|
||||||
@@ -33,7 +34,7 @@ export interface UpdDocument {
|
|||||||
fileName: string
|
fileName: string
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface ApiErrorLog {
|
export interface ApiDebugInfo {
|
||||||
request: {
|
request: {
|
||||||
method: string
|
method: string
|
||||||
url: string
|
url: string
|
||||||
@@ -44,12 +45,14 @@ export interface ApiErrorLog {
|
|||||||
statusCode: number
|
statusCode: number
|
||||||
headers: Record<string, string>
|
headers: Record<string, string>
|
||||||
body: unknown
|
body: unknown
|
||||||
|
errorCode?: string
|
||||||
|
errorMessage?: string
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface ApiErrorResponse {
|
export interface ApiErrorResponse {
|
||||||
error: string
|
error: string
|
||||||
debugInfo?: ApiErrorLog
|
debugInfo?: ApiDebugInfo
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface UpdUploadResponse {
|
export interface UpdUploadResponse {
|
||||||
|
|||||||
@@ -0,0 +1,69 @@
|
|||||||
|
# Соответствие ID складов Wildberries
|
||||||
|
|
||||||
|
## Официальные API (требуется API-ключ продавца)
|
||||||
|
|
||||||
|
### Suppliers API
|
||||||
|
```
|
||||||
|
GET https://suppliers-api.wildberries.ru/api/v3/warehouses
|
||||||
|
Header: Authorization: <API-ключ>
|
||||||
|
```
|
||||||
|
Возвращает полный список складов с ID и названиями.
|
||||||
|
|
||||||
|
### Statistics API
|
||||||
|
```
|
||||||
|
GET https://statistics-api.wildberries.ru/api/v1/warehouses
|
||||||
|
Header: Authorization: <API-ключ>
|
||||||
|
```
|
||||||
|
|
||||||
|
## Публичные веб-ресурсы
|
||||||
|
|
||||||
|
### Карта складов wbarcode.ru
|
||||||
|
- **Список всех складов (названия):** https://wbarcode.ru/warehouses
|
||||||
|
- **Страницы отдельных складов:** `/warehouses/<slug>` (например, `/warehouses/koledino`, `/warehouses/novosibirsk`, `/warehouses/domodedovo`)
|
||||||
|
- Содержит адреса, координаты, информацию о режиме работы (но ID складов на страницах не отображаются, только названия)
|
||||||
|
|
||||||
|
### Статья с перечнем складов (litestat.io)
|
||||||
|
- https://litestat.io/blog/sklady-wildberries-adresa-zony-pokrytiya-koordinaty/
|
||||||
|
- Адреса и описания основных складов, но без ID
|
||||||
|
|
||||||
|
### Карта складов WB prod
|
||||||
|
- https://wbprod.ru/zony-pokritiya-skladov-wb/Novosibirsk/
|
||||||
|
|
||||||
|
### Wildberries Edu
|
||||||
|
- https://wildberries-edu.ru/sklady-wildberries/
|
||||||
|
|
||||||
|
## Community-ресурсы (GitHub)
|
||||||
|
|
||||||
|
Репозитории, в которых могут быть JSON-файлы с маппингом:
|
||||||
|
- https://github.com/eslazarev/wildberries-sdk — OpenAPI-спецификации WB API
|
||||||
|
- https://github.com/ilyautov/marketplaces-mcp-ru — MCP-сервер для WB, маппинги внутри
|
||||||
|
- https://github.com/salacoste/daytona-wildberries-typescript-sdk — TypeScript SDK
|
||||||
|
|
||||||
|
Поискать по GitHub: `wb warehouses`, `wb-warehouses`, `wildberries warehouses list`, `warehouses.json`
|
||||||
|
|
||||||
|
## Кабинет продавца
|
||||||
|
https://seller.wildberries.ru — при создании поставки или в разделе «Склады» видны ID.
|
||||||
|
|
||||||
|
## Известные ID складов (справочно)
|
||||||
|
|
||||||
|
| ID | Название | Регион |
|
||||||
|
|---------|------------------------------|-----------------------|
|
||||||
|
| 120602 | Коледино | Московская область |
|
||||||
|
| 686 | Новосибирск | Новосибирская область |
|
||||||
|
| 116433 | Домодедово (Белые Столбы) | Московская область |
|
||||||
|
| 117986 | Казань | Татарстан |
|
||||||
|
| 118535 | Екатеринбург (Кольцово) | Свердловская область |
|
||||||
|
| 121709 | Санкт-Петербург (Шушары) | Ленинградская область |
|
||||||
|
| 121710 | Подольск | Московская область |
|
||||||
|
| 98591 | Краснодар | Краснодарский край |
|
||||||
|
| 207743 | Хабаровск | Хабаровский край |
|
||||||
|
| 98774 | Горячий Ключ | Краснодарский край |
|
||||||
|
| 119698 | Ростов-на-Дону | Ростовская область |
|
||||||
|
|
||||||
|
## Пути к статическим файлам WB (могут не работать)
|
||||||
|
```
|
||||||
|
https://catalog.wb.ru/catalog/warehouse/v1/warehouses
|
||||||
|
https://static-basket-01.wb.ru/vol0/data/warehouses.json
|
||||||
|
https://static-basket-01.wbbasket.ru/vol0/data/warehouses.json
|
||||||
|
```
|
||||||
|
Большинство эндпоинтов WB защищены антибот-системой (498 ошибка).
|
||||||
Reference in New Issue
Block a user