refactor(repo): переход на pnpm monorepo с shadcn/ui и Fastify+Drizzle
Frontend:
- apps/web (Vite+TS, TanStack Router/Query, shadcn/ui @cfdm/ui base-nova)
- 10 страниц в routes/_auth/, Recharts через shadcn Chart, lucide-react
- формы на RHF + Zod (FormSheet/FormField)
- удалены Tabler, Chart.js, react-router-dom
Backend (параллельный трек):
- apps/api (Fastify 5 + Drizzle + better-sqlite3)
- packages/db: Drizzle-схема и repositories по сущностям
- packages/shared: Zod-контракты
- роуты с валидацией и единым форматом ошибок { error: { code, message } }
- sync/backup — заглушки 501 (billmanager-адаптеры переносятся отдельно)
- legacy Express оставлен как runtime по умолчанию (RUNTIME=express)
Infra:
- Dockerfile multi-stage под pnpm workspaces
- .dockerignore и docker-compose обновлены под monorepo
Rules:
- удалены нерелевантные правила (rust, cloudflare, server/frontend-conventions)
- project-structure.mdc и AGENTS.md переписаны под monorepo
- frontend-shadcn.mdc, shadcn-ui-production.mdc, sqlite.mdc обновлены
Co-authored-by: Cursor <[email protected]>
This commit is contained in:
@@ -0,0 +1,30 @@
|
||||
/**
|
||||
* BILLmanager 6 API HTTP client
|
||||
* @see https://www.ispsystem.com/docs/b6c/developer-section/working-with-api/guide-to-ispsystem-software-api
|
||||
*/
|
||||
|
||||
/**
|
||||
* @param {string} baseUrl - e.g. https://bill.example.com:1500/billmgr
|
||||
* @param {string} authinfo - username:password
|
||||
* @param {string} func - API function name (vds, payment, dedic)
|
||||
* @param {Record<string, string>} [params] - additional query params
|
||||
* @returns {Promise<any>}
|
||||
*/
|
||||
export async function billmanagerRequest(baseUrl, authinfo, func, params = {}) {
|
||||
const url = new URL(baseUrl)
|
||||
url.searchParams.set('authinfo', authinfo)
|
||||
url.searchParams.set('out', 'bjson')
|
||||
url.searchParams.set('func', func)
|
||||
for (const [k, v] of Object.entries(params)) {
|
||||
if (v != null && v !== '') url.searchParams.set(k, String(v))
|
||||
}
|
||||
const res = await fetch(url.toString(), { method: 'GET' })
|
||||
if (!res.ok) {
|
||||
throw new Error(`BILLmanager API HTTP ${res.status}: ${res.statusText}`)
|
||||
}
|
||||
const data = await res.json()
|
||||
if (data.error) {
|
||||
throw new Error(data.error.msg || data.error.$t || 'BILLmanager API error')
|
||||
}
|
||||
return data
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
/**
|
||||
* BILLmanager 6 API adapter
|
||||
* @see https://www.ispsystem.com/docs/b6c/developer-section/working-with-api/guide-to-ispsystem-software-api
|
||||
* @see https://www.ispsystem.com/docs/b6c/developer-section/billmanager-api/virtual-private-servers-vds
|
||||
* @see https://www.ispsystem.com/docs/b6c/developer-section/billmanager-api/payments-payment
|
||||
*/
|
||||
|
||||
export { testConnection, fetchVds, fetchDashboardInfo, fetchPayments, fetchVdsOrderPricelist, fetchVdsOrderPricelistAllDatacenters } from './operations.js'
|
||||
export { syncFromBillmanager } from './sync.js'
|
||||
@@ -0,0 +1,94 @@
|
||||
/**
|
||||
* BILLmanager API response → vps-tracker model mappers
|
||||
*/
|
||||
|
||||
import { parsePricelist } from './parsers.js'
|
||||
|
||||
/** BILLmanager VDS status: 1=ordered, 2=active, 3=suspended, 4=deleted, 5=processing */
|
||||
const VDS_STATUS_MAP = {
|
||||
1: 'active',
|
||||
2: 'active',
|
||||
3: 'paused',
|
||||
4: 'archived',
|
||||
5: 'active',
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {object} item - BILLmanager vds item
|
||||
* @returns {object} vps-tracker vps shape
|
||||
*/
|
||||
export function mapVdsToVps(item, providerId, providerAccountId) {
|
||||
const status = VDS_STATUS_MAP[Number(item.item_status_orig ?? item.item_status)] ?? 'active'
|
||||
// cost: "100.00 RUB / Месяц" — приоритет для ежемесячного платежа; item_cost — запасной
|
||||
const costStr = String(item.cost || '').replace(/[^\d.-]/g, '')
|
||||
const cost = parseFloat(costStr) || parseFloat(item.item_cost) || 0
|
||||
const createdate = item.createdate || ''
|
||||
const expiredate = item.real_expiredate || item.expiredate || ''
|
||||
const ip = (item.ip || '').trim()
|
||||
const domain = (item.domain || '').trim()
|
||||
const datacenter = (item.datacentername || item.datacenter || '').trim()
|
||||
const ostempl = (item.ostempl || '').trim()
|
||||
const currency = (item.currency_str || 'RUB').toString().trim() || 'RUB'
|
||||
|
||||
const pricelist = item.pricelist || item.tariff || item.plan || ''
|
||||
const parsed = parsePricelist(pricelist)
|
||||
|
||||
return {
|
||||
externalId: String(item.id || ''),
|
||||
ip: ip || domain || `bm-${item.id}`,
|
||||
dns: domain || ip || '',
|
||||
ipv6: '',
|
||||
additionalIps: [],
|
||||
providerId,
|
||||
providerAccountId,
|
||||
country: '',
|
||||
city: '',
|
||||
datacenter,
|
||||
os: ostempl,
|
||||
vcpu: parsed.vcpu || 0,
|
||||
ramGb: parsed.ramGb || 0,
|
||||
diskGb: parsed.diskGb || 0,
|
||||
diskType: parsed.diskType || 'NVMe',
|
||||
virtualization: parsed.virtualization || 'KVM',
|
||||
bandwidthTb: 0,
|
||||
sshPort: 22,
|
||||
rootUser: 'root',
|
||||
purpose: '',
|
||||
environment: 'prod',
|
||||
project: '',
|
||||
monitoringEnabled: false,
|
||||
backupEnabled: false,
|
||||
status,
|
||||
tariffType: 'monthly',
|
||||
currency: currency || 'RUB',
|
||||
dailyRate: null,
|
||||
monthlyRate: cost || null,
|
||||
createdAt: createdate ? createdate.slice(0, 10) : new Date().toISOString().slice(0, 10),
|
||||
paidUntil: expiredate ? expiredate.slice(0, 10) : '',
|
||||
notes: `bm-${item.id}`,
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {object} item - BILLmanager payment item
|
||||
* @returns {object|null} vps-tracker payment shape or null if not credited
|
||||
*/
|
||||
export function mapPaymentToPayment(item, providerAccountId) {
|
||||
const rawAmount = item.subaccountamount_iso || item.paymethodamount_iso || '0'
|
||||
const amount = parseFloat(String(rawAmount).replace(/[^\d.-]/g, '')) || 0
|
||||
const createDate = item.create_date || item.createdate || ''
|
||||
const dateStr = createDate ? String(createDate).slice(0, 10) : new Date().toISOString().slice(0, 10)
|
||||
// status_orig / real_status = "4" (credited), item.status может быть "Зачислен"
|
||||
const statusNum = Number(item.status_orig ?? item.real_status ?? item.status)
|
||||
if (statusNum !== 4) return null
|
||||
return {
|
||||
externalId: String(item.id || ''),
|
||||
type: 'provider_balance_topup',
|
||||
date: dateStr,
|
||||
amount,
|
||||
currency: (String(item.subaccountamount_iso || item.paymethodamount_iso || '').match(/([A-Z]{3})\b/) || [])[1] || 'USD',
|
||||
providerAccountId,
|
||||
vpsId: null,
|
||||
note: `BILLmanager #${item.number || item.id}`,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,169 @@
|
||||
/**
|
||||
* BILLmanager API operations — fetch VDS, payments, dashboard, tariffs
|
||||
*/
|
||||
|
||||
import { billmanagerRequest } from './client.js'
|
||||
import { extractList, elemToObject, parseTariffDesc, parseDatacenterName, extractTariflist } from './parsers.js'
|
||||
|
||||
/**
|
||||
* @param {string} baseUrl
|
||||
* @param {string} authinfo
|
||||
* @returns {Promise<object[]>} list of vps objects (raw BILLmanager format)
|
||||
*/
|
||||
export async function fetchVds(baseUrl, authinfo) {
|
||||
const data = await billmanagerRequest(baseUrl, authinfo, 'vds')
|
||||
const elems = extractList(data, 'vds')
|
||||
return elems.map((e) => elemToObject(e))
|
||||
}
|
||||
|
||||
/**
|
||||
* Получить текущий баланс аккаунта (dashboard.info)
|
||||
* @param {string} baseUrl - e.g. https://billing.example.com/billmgr
|
||||
* @param {string} authinfo - username:password
|
||||
* @param {object} [opts] - { fallbackCurrency } — валюта аккаунта, если API не возвращает
|
||||
* @returns {Promise<{ balance: number, currency: string, enoughmoneyto?: string, realbalance?: string }>}
|
||||
*/
|
||||
export async function fetchDashboardInfo(baseUrl, authinfo, opts = {}) {
|
||||
const data = await billmanagerRequest(baseUrl, authinfo, 'dashboard.info', {
|
||||
dashboard: 'info',
|
||||
sfrom: 'ajax',
|
||||
})
|
||||
const elems = extractList(data, 'dashboard') || (Array.isArray(data.elem) ? data.elem : [])
|
||||
const item = elems.length > 0 ? elemToObject(elems[0]) : {}
|
||||
const balanceStr = String(item.realbalance || item.balance || item.available || '0')
|
||||
const amount = parseFloat(balanceStr.replace(/[^\d.,-]/g, '').replace(',', '.')) || 0
|
||||
let currency = (balanceStr.match(/([A-Z]{3})\b/) || [])[1]
|
||||
if (!currency) {
|
||||
if (balanceStr.includes('€') || balanceStr.includes('EUR')) currency = 'EUR'
|
||||
else if (balanceStr.includes('$') || balanceStr.includes('USD')) currency = 'USD'
|
||||
else if (balanceStr.includes('₽') || balanceStr.includes('RUB')) currency = 'RUB'
|
||||
else if (balanceStr.includes('£')) currency = 'GBP'
|
||||
else currency = opts.fallbackCurrency || 'RUB'
|
||||
}
|
||||
return {
|
||||
balance: amount,
|
||||
currency: currency || opts.fallbackCurrency || 'RUB',
|
||||
enoughmoneyto: item.enoughmoneyto || '',
|
||||
realbalance: item.realbalance || '',
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string} baseUrl - e.g. https://billing.example.com/billmgr
|
||||
* @param {string} authinfo - username:password
|
||||
* @param {object} [opts] - { createdatestart, createdateend } — опционально, не все API поддерживают
|
||||
* @returns {Promise<object[]>} list of payment objects
|
||||
*/
|
||||
export async function fetchPayments(baseUrl, authinfo, opts = {}) {
|
||||
const params = {}
|
||||
if (opts.createdatestart) params.createdatestart = opts.createdatestart
|
||||
if (opts.createdateend) params.createdateend = opts.createdateend
|
||||
if (opts.createdate === 'other') params.createdate = 'other'
|
||||
if (opts.filter === 'on') params.filter = 'on'
|
||||
if (opts.status != null) params.status = String(opts.status)
|
||||
const data = await billmanagerRequest(baseUrl, authinfo, 'payment', params)
|
||||
const elems = extractList(data, 'payment')
|
||||
return elems.map((e) => elemToObject(e))
|
||||
}
|
||||
|
||||
/**
|
||||
* Получить список активных тарифов для заказа VDS (vds.order) для одного датацентра
|
||||
* @param {string} baseUrl
|
||||
* @param {string} authinfo
|
||||
* @param {object} [opts] - { plid, period, datacenter }
|
||||
* @returns {Promise<{ tariffItems: object[], slist: object }>}
|
||||
*/
|
||||
export async function fetchVdsOrderPricelist(baseUrl, authinfo, opts = {}) {
|
||||
const params = {
|
||||
plid: opts.plid || '',
|
||||
sfrom: 'ajax',
|
||||
}
|
||||
if (opts.period) params.period = opts.period
|
||||
if (opts.datacenter) params.datacenter = opts.datacenter
|
||||
|
||||
const data = await billmanagerRequest(baseUrl, authinfo, 'vds.order', params)
|
||||
|
||||
const tariflist = extractTariflist(data)
|
||||
const slist = data?.list?.slist ?? data?.slist ?? {}
|
||||
if (tariflist.length === 0) return { tariffItems: [], slist }
|
||||
|
||||
const tariffItems = tariflist.map((rawItem) => {
|
||||
const item = elemToObject(rawItem)
|
||||
const parsed = parseTariffDesc(item.desc || '')
|
||||
const descClean = (item.desc || '').replace(/<[^>]+>/g, ' ').replace(/\s+/g, ' ').trim()
|
||||
const name = parsed.name || parsed.cpuModel || item.price?.split(' ')[0] || '—'
|
||||
return {
|
||||
externalId: String(item.pricelist || ''),
|
||||
name,
|
||||
desc: descClean,
|
||||
vcpu: parsed.vcpu,
|
||||
ramGb: parsed.ramGb,
|
||||
diskGb: parsed.diskGb,
|
||||
diskType: parsed.diskType,
|
||||
virtualization: parsed.virtualization,
|
||||
channel: parsed.channel,
|
||||
location: parsed.location,
|
||||
cpuModel: parsed.cpuModel,
|
||||
orderAvailable: (item.order_available || '').toLowerCase() === 'on',
|
||||
price: item.price || '',
|
||||
}
|
||||
})
|
||||
|
||||
return { tariffItems, slist }
|
||||
}
|
||||
|
||||
/**
|
||||
* Получить тарифы по всем датацентрам — отдельный запрос на каждый ДЦ.
|
||||
* @param {string} baseUrl
|
||||
* @param {string} authinfo
|
||||
* @returns {Promise<{ tariffItems: object[], slist: object }>}
|
||||
*/
|
||||
export async function fetchVdsOrderPricelistAllDatacenters(baseUrl, authinfo) {
|
||||
const initial = await fetchVdsOrderPricelist(baseUrl, authinfo)
|
||||
const slist = initial.slist || {}
|
||||
const datacenters = Array.isArray(slist.datacenter) ? slist.datacenter : []
|
||||
|
||||
if (datacenters.length === 0) {
|
||||
return { tariffItems: initial.tariffItems, slist }
|
||||
}
|
||||
|
||||
const allTariffItems = []
|
||||
|
||||
for (let i = 0; i < datacenters.length; i++) {
|
||||
const dc = datacenters[i]
|
||||
const dcKey = String(dc.k ?? dc.key ?? '')
|
||||
const dcName = String(dc.v ?? dc.value ?? dc.name ?? '')
|
||||
const { country, location } = parseDatacenterName(dcName)
|
||||
|
||||
const result = i === 0 ? initial : await fetchVdsOrderPricelist(baseUrl, authinfo, { datacenter: dcKey })
|
||||
for (const t of result.tariffItems) {
|
||||
allTariffItems.push({
|
||||
...t,
|
||||
datacenterKey: dcKey,
|
||||
datacenterName: dcName,
|
||||
country,
|
||||
location: location || dcName,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
return { tariffItems: allTariffItems, slist }
|
||||
}
|
||||
|
||||
/**
|
||||
* Test API connection — запрос списка VDS
|
||||
* @param {string} baseUrl
|
||||
* @param {string} authinfo - username:password
|
||||
* @returns {Promise<{ ok: boolean, error?: string, vdsCount?: number }>}
|
||||
*/
|
||||
export async function testConnection(baseUrl, authinfo) {
|
||||
if (!baseUrl?.trim() || !authinfo?.trim()) {
|
||||
return { ok: false, error: 'Укажите URL и учётные данные' }
|
||||
}
|
||||
try {
|
||||
const items = await fetchVds(baseUrl.trim(), authinfo.trim())
|
||||
return { ok: true, vdsCount: items?.length ?? 0 }
|
||||
} catch (err) {
|
||||
return { ok: false, error: err.message || 'Ошибка подключения' }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,252 @@
|
||||
/**
|
||||
* BILLmanager API response parsers
|
||||
*/
|
||||
|
||||
/**
|
||||
* Parse BILLmanager JSON list response.
|
||||
* bjson: { elem: [ {...}, {...} ] } или { data: { elem: [...] } }
|
||||
* xml/json: { doc: { vds: { elem: [...] } } }
|
||||
*/
|
||||
export function extractList(data, key) {
|
||||
if (Array.isArray(data.elem)) return data.elem
|
||||
if (data.data?.elem) return Array.isArray(data.data.elem) ? data.data.elem : [data.data.elem]
|
||||
const doc = data.doc || data
|
||||
let list = doc[key]
|
||||
if (!list) return []
|
||||
if (Array.isArray(list)) return list
|
||||
if (list.elem) {
|
||||
const elems = Array.isArray(list.elem) ? list.elem : [list.elem]
|
||||
return elems
|
||||
}
|
||||
return []
|
||||
}
|
||||
|
||||
/**
|
||||
* Extract flat object from BILLmanager elem (can be array of { $name, $t } or already flat object)
|
||||
*/
|
||||
export function elemToObject(elem) {
|
||||
if (!elem) return {}
|
||||
if (Array.isArray(elem)) {
|
||||
const obj = {}
|
||||
for (const e of elem) {
|
||||
const name = e.$name || e.name
|
||||
const val = e.$t ?? e.$ ?? e
|
||||
if (name) obj[name] = typeof val === 'object' && val !== null ? (val.$t ?? val.$ ?? JSON.stringify(val)) : val
|
||||
}
|
||||
return obj
|
||||
}
|
||||
return typeof elem === 'object' ? elem : {}
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse pricelist string: "KVM SSD Start (1 CPU/768 MB RAM/7 GB SSD)"
|
||||
* @returns {{ vcpu: number, ramGb: number, diskGb: number, diskType: string, virtualization: string }}
|
||||
*/
|
||||
export function parsePricelist(pricelist) {
|
||||
const s = String(pricelist || '')
|
||||
let vcpu = 0
|
||||
let ramGb = 0
|
||||
let diskGb = 0
|
||||
let diskType = 'NVMe'
|
||||
let virtualization = 'KVM'
|
||||
|
||||
const cpuMatch = s.match(/(\d+)\s*(?:CPU|СPU)/i)
|
||||
if (cpuMatch) vcpu = parseInt(cpuMatch[1], 10) || 0
|
||||
|
||||
const ramMbMatch = s.match(/(\d+)\s*MB\s*RAM/i)
|
||||
if (ramMbMatch) ramGb = Math.max(1, Math.round((parseInt(ramMbMatch[1], 10) || 0) / 1024))
|
||||
else {
|
||||
const ramGbMatch = s.match(/(\d+)\s*GB\s*RAM/i)
|
||||
if (ramGbMatch) ramGb = parseInt(ramGbMatch[1], 10) || 0
|
||||
}
|
||||
|
||||
const diskMatch = s.match(/(\d+)\s*GB\s*(SSD|NVMe|HDD)/i)
|
||||
if (diskMatch) {
|
||||
diskGb = parseInt(diskMatch[1], 10) || 0
|
||||
diskType = diskMatch[2] || 'NVMe'
|
||||
}
|
||||
|
||||
if (/\bKVM\b/i.test(s)) virtualization = 'KVM'
|
||||
else if (/\bOpenVZ\b/i.test(s)) virtualization = 'OpenVZ'
|
||||
else if (/\bLXC\b/i.test(s)) virtualization = 'LXC'
|
||||
|
||||
return { vcpu, ramGb, diskGb, diskType, virtualization }
|
||||
}
|
||||
|
||||
/**
|
||||
* Парсит описание тарифа из vds.order.pricelist (desc)
|
||||
* Поддерживает два формата: текстовый (Firstbyte) и HTML (Selectel и др.)
|
||||
* @param {string} desc - HTML или текстовое описание тарифа
|
||||
* @returns {{ name: string, vcpu: number, ramGb: number, diskGb: number, diskType: string, virtualization: string, channel: string, location: string, cpuModel: string }}
|
||||
*/
|
||||
export function parseTariffDesc(desc) {
|
||||
const s = String(desc || '')
|
||||
let name = ''
|
||||
let vcpu = 0
|
||||
let ramGb = 0
|
||||
let diskGb = 0
|
||||
let diskType = 'SSD'
|
||||
let virtualization = 'KVM'
|
||||
let channel = ''
|
||||
let location = ''
|
||||
let cpuModel = ''
|
||||
|
||||
const firstLine = s.split(/\r?\n|<br\s*\/?>/i)[0]?.trim() || ''
|
||||
name = firstLine.replace(/<[^>]+>/g, '').trim()
|
||||
|
||||
// Формат 1: "Процессор: 1 ядро", "Память: 1 GB", "Диск: 20 GB SSD", "Канал: 200Mb/s"
|
||||
const cpuMatch = s.match(/Процессор:\s*(\d+)\s*(?:ядро|ядра|ядер)/i)
|
||||
if (cpuMatch) vcpu = parseInt(cpuMatch[1], 10) || 0
|
||||
|
||||
const ramMbMatch = s.match(/Память:\s*(\d+)\s*MB/i)
|
||||
if (ramMbMatch) ramGb = Math.max(0.5, Math.round((parseInt(ramMbMatch[1], 10) || 0) / 1024 * 10) / 10)
|
||||
else {
|
||||
const ramGbMatch = s.match(/Память:\s*(\d+)\s*GB/i)
|
||||
if (ramGbMatch) ramGb = parseInt(ramGbMatch[1], 10) || 0
|
||||
}
|
||||
|
||||
const diskMatch = s.match(/Диск:\s*(\d+)\s*GB\s*(SSD|SAS|HDD|NVMe)/i)
|
||||
if (diskMatch) {
|
||||
diskGb = parseInt(diskMatch[1], 10) || 0
|
||||
diskType = diskMatch[2] || 'SSD'
|
||||
}
|
||||
|
||||
const channelMatch = s.match(/Канал:\s*(\d+Mb\/s)/i)
|
||||
if (channelMatch) channel = channelMatch[1]
|
||||
|
||||
if (/\bKVM\b/i.test(s)) virtualization = 'KVM'
|
||||
else if (/\bOpenVZ\b/i.test(s)) virtualization = 'OpenVZ'
|
||||
else if (/\bLXC\b/i.test(s)) virtualization = 'LXC'
|
||||
|
||||
// Формат 2 (HTML): "Публичная сеть: 250 Мбит/с", "Локация: Москва, Россия", "Процессор: Ryzen 7 5800X", "NVMe накопитель"
|
||||
if (!channel) {
|
||||
const netMatch = s.match(/(?:Публичная сеть|Канал)[:\s]*\*?\*?(\d+)\s*Мбит/i)
|
||||
if (netMatch) channel = `${netMatch[1]} Мбит/с`
|
||||
}
|
||||
if (!location) {
|
||||
const locMatch = s.match(/Локация[:\s]*([^;]+)/i)
|
||||
if (locMatch) location = locMatch[1].replace(/<[^>]+>/g, '').trim()
|
||||
}
|
||||
if (!cpuModel) {
|
||||
const procMatch = s.match(/Процессор[:\s]*([^;]+?)(?:\s+до\s|$)/i)
|
||||
if (procMatch) cpuModel = procMatch[1].replace(/<[^>]+>/g, '').trim()
|
||||
}
|
||||
if (!diskType || diskType === 'SSD') {
|
||||
if (/\bNVMe\b/i.test(s)) diskType = 'NVMe'
|
||||
else if (/\bSAS\b/i.test(s)) diskType = 'SAS'
|
||||
else if (/\bHDD\b/i.test(s)) diskType = 'HDD'
|
||||
else if (/\bSSD\b/i.test(s)) diskType = 'SSD'
|
||||
}
|
||||
|
||||
return { name, vcpu, ramGb, diskGb, diskType, virtualization, channel, location, cpuModel }
|
||||
}
|
||||
|
||||
/**
|
||||
* Парсит название датацентра для извлечения страны и локации
|
||||
* @param {string} dcName - название ДЦ, напр. "1 Датацентр Россия, Москва", "[DE] Франкфурт", "Франция"
|
||||
* @returns {{ country: string, location: string }}
|
||||
*/
|
||||
export function parseDatacenterName(dcName) {
|
||||
const s = String(dcName || '').trim()
|
||||
if (!s) return { country: '', location: '' }
|
||||
|
||||
const COUNTRY_CODE_MAP = {
|
||||
DE: 'Германия',
|
||||
FI: 'Финляндия',
|
||||
RU: 'Россия',
|
||||
FR: 'Франция',
|
||||
GB: 'Великобритания',
|
||||
NL: 'Нидерланды',
|
||||
US: 'США',
|
||||
SE: 'Швеция',
|
||||
NO: 'Норвегия',
|
||||
BE: 'Бельгия',
|
||||
CH: 'Швейцария',
|
||||
CZ: 'Чехия',
|
||||
CA: 'Канада',
|
||||
LV: 'Латвия',
|
||||
LT: 'Литва',
|
||||
EE: 'Эстония',
|
||||
PL: 'Польша',
|
||||
IT: 'Италия',
|
||||
DK: 'Дания',
|
||||
AU: 'Австралия',
|
||||
ES: 'Испания',
|
||||
SG: 'Сингапур',
|
||||
}
|
||||
|
||||
// "[DE] Франкфурт | AMD EPYC" -> country: DE/Германия, location: Франкфурт
|
||||
const codeMatch = s.match(/\[([A-Z]{2})\]\s*([^|]+)/)
|
||||
if (codeMatch) {
|
||||
const code = codeMatch[1]
|
||||
const loc = codeMatch[2].trim()
|
||||
return { country: COUNTRY_CODE_MAP[code] || code, location: loc }
|
||||
}
|
||||
|
||||
// "N Датацентр Страна, Город" или "Датацентр Страна, Город"
|
||||
const dcMatch = s.match(/(?:\d+\s+)?Датацентр\s+([^,]+),\s*(.+)/i)
|
||||
if (dcMatch) {
|
||||
return { country: dcMatch[1].trim(), location: dcMatch[2].trim() }
|
||||
}
|
||||
|
||||
// "Страна, Город" (без слова Датацентр)
|
||||
const commaMatch = s.match(/^([^,]+),\s*(.+)$/)
|
||||
if (commaMatch) {
|
||||
return { country: commaMatch[1].trim(), location: commaMatch[2].trim() }
|
||||
}
|
||||
|
||||
// Только страна: "Франция", "Россия", "Германия", "Чехия" и т.д.
|
||||
const countryOnly = [
|
||||
'Россия', 'Чехия', 'Нидерланды', 'Франция', 'Великобритания', 'Германия',
|
||||
'Финляндия', 'Швеция', 'Норвегия', 'Бельгия', 'Швейцария', 'Канада',
|
||||
'Латвия', 'Литва', 'Эстония', 'Польша', 'Италия', 'Дания', 'Австралия',
|
||||
'Испания', 'Сингапур', 'США', 'Азия', 'Европа',
|
||||
]
|
||||
for (const c of countryOnly) {
|
||||
if (s === c || s.startsWith(c + ',') || s.startsWith(c + ' ')) {
|
||||
const rest = s.slice(c.length).replace(/^[,\s]+/, '')
|
||||
return { country: c, location: rest }
|
||||
}
|
||||
}
|
||||
|
||||
// "ММТС-9", "Adman", "Европа DC1", "Москва DC3" — по ключевым словам
|
||||
if (/ММТС|Adman|Москва/i.test(s)) {
|
||||
return { country: 'Россия', location: s }
|
||||
}
|
||||
if (/Европа/i.test(s)) {
|
||||
return { country: 'Европа', location: s.replace(/Европа\s*/i, '').trim() || s }
|
||||
}
|
||||
|
||||
// "США | Ryzen 9 9950X" — страна до |
|
||||
const pipeMatch = s.match(/^([^|]+)\s*\|/)
|
||||
if (pipeMatch) {
|
||||
const part = pipeMatch[1].trim()
|
||||
for (const c of countryOnly) {
|
||||
if (part.includes(c)) return { country: c, location: '' }
|
||||
}
|
||||
return { country: part, location: '' }
|
||||
}
|
||||
|
||||
return { country: s, location: '' }
|
||||
}
|
||||
|
||||
/**
|
||||
* Извлечь tariflist из ответа vds.order (поддержка разных форматов BILLmanager)
|
||||
* @param {object} data - сырой ответ API
|
||||
* @returns {Array}
|
||||
*/
|
||||
export function extractTariflist(data) {
|
||||
if (!data) return []
|
||||
const listNode = data.list ?? data.doc?.list ?? data.doc
|
||||
if (!listNode) return []
|
||||
|
||||
// tariflist / tarifflist / pricelist — разные варианты названия
|
||||
let list = listNode.tariflist ?? listNode.tarifflist ?? listNode.pricelist
|
||||
if (Array.isArray(list)) return list
|
||||
|
||||
// elem-формат (как в vds, payment)
|
||||
const elems = listNode.elem
|
||||
if (elems) return Array.isArray(elems) ? elems : [elems]
|
||||
|
||||
return []
|
||||
}
|
||||
@@ -0,0 +1,255 @@
|
||||
/**
|
||||
* Sync BILLmanager data into vps-tracker DB
|
||||
*/
|
||||
|
||||
import { fetchVds, fetchPayments, fetchDashboardInfo, fetchVdsOrderPricelistAllDatacenters } from './operations.js'
|
||||
import { mapVdsToVps, mapPaymentToPayment } from './mappers.js'
|
||||
|
||||
/**
|
||||
* Sync BILLmanager data into vps-tracker DB
|
||||
* @param {object} account - provider_account с apiCredentials и apiBaseUrl (URL с хостера или уже подставленный)
|
||||
* @param {object} db - getDb() wrapper
|
||||
* @param {object} [opts] - { paymentDaysBack, skipTariffs, skipVpsPayments }
|
||||
* @returns {{ vpsCount: number, paymentsCount: number, tariffsCount: number, balance?: object }}
|
||||
*/
|
||||
export async function syncFromBillmanager(account, db, opts = {}) {
|
||||
const { skipTariffs = false, skipVpsPayments = false } = opts
|
||||
const { apiBaseUrl, apiCredentials, providerId, id: accountId } = account
|
||||
if (!apiBaseUrl?.trim() || !apiCredentials?.trim()) {
|
||||
throw new Error('API URL and credentials are required')
|
||||
}
|
||||
const authinfo = apiCredentials.trim()
|
||||
|
||||
const fetchVpsPayments = !skipVpsPayments
|
||||
const fetchTariffs = !skipTariffs
|
||||
|
||||
const [vdsItems, paymentItems, dashboardInfo, tariffResult] = await Promise.all([
|
||||
fetchVpsPayments ? fetchVds(apiBaseUrl, authinfo) : [],
|
||||
fetchVpsPayments ? fetchPayments(apiBaseUrl, authinfo, {}) : [],
|
||||
fetchVpsPayments ? fetchDashboardInfo(apiBaseUrl, authinfo, { fallbackCurrency: account.currency }).catch(() => null) : null,
|
||||
fetchTariffs ? fetchVdsOrderPricelistAllDatacenters(apiBaseUrl, authinfo).catch((err) => {
|
||||
console.warn('fetchVdsOrderPricelistAllDatacenters failed:', err.message)
|
||||
return { tariffItems: [], slist: {} }
|
||||
}) : { tariffItems: [], slist: {} },
|
||||
])
|
||||
const { tariffItems = [], slist = {} } = tariffResult || {}
|
||||
|
||||
let vpsCount = 0
|
||||
/** @type {{ added: { id: string, label: string }[], updated: { id: string, label: string, fields: string[] }[], paymentsAdded: number }} */
|
||||
const syncSummary = { added: [], updated: [], paymentsAdded: 0 }
|
||||
if (fetchVpsPayments) {
|
||||
const vpsInsertSql = `INSERT INTO vps (id, ip, ipv6, additionalIps, dns, providerId, providerAccountId, country, city, datacenter, os, vcpu, ramGb, diskGb, diskType, virtualization, bandwidthTb, sshPort, rootUser, purpose, environment, project, projectId, monitoringEnabled, backupEnabled, status, tariffType, currency, dailyRate, monthlyRate, createdAt, paidUntil, notes, userOverrides)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`
|
||||
const vpsUpdateSql = `UPDATE vps SET ip=?, ipv6=?, additionalIps=?, dns=?, country=?, city=?, datacenter=?, os=?, status=?, tariffType=?, currency=?, dailyRate=?, monthlyRate=?, paidUntil=?, notes=?
|
||||
WHERE id=?`
|
||||
|
||||
const SYNC_UPDATE_FIELDS = ['country', 'city', 'datacenter', 'os', 'notes', 'status', 'tariffType', 'currency', 'dailyRate', 'monthlyRate', 'paidUntil']
|
||||
|
||||
const normVal = (v) => {
|
||||
if (v == null || v === '') return ''
|
||||
if (typeof v === 'number') return Number.isFinite(v) ? String(v) : ''
|
||||
return String(v)
|
||||
}
|
||||
|
||||
for (const item of vdsItems) {
|
||||
const vps = mapVdsToVps(item, providerId, accountId)
|
||||
const id = `vps-bm-${accountId}-${vps.externalId}`
|
||||
const additionalIps = JSON.stringify(vps.additionalIps || [])
|
||||
const dailyRate = vps.dailyRate
|
||||
const monthlyRate = vps.monthlyRate
|
||||
const paidUntil = vps.paidUntil || ''
|
||||
const notes = vps.notes ? `${vps.notes} [bm-${vps.externalId}]` : `bm-${vps.externalId}`
|
||||
|
||||
const existing = db.prepare('SELECT * FROM vps WHERE providerAccountId = ? AND (ip = ? OR notes LIKE ?)').get(accountId, vps.ip, `%bm-${vps.externalId}%`)
|
||||
if (existing) {
|
||||
let userOverrides = []
|
||||
try {
|
||||
userOverrides = existing.userOverrides ? JSON.parse(existing.userOverrides) : []
|
||||
} catch {
|
||||
userOverrides = []
|
||||
}
|
||||
const merged = {
|
||||
ip: vps.ip,
|
||||
ipv6: vps.ipv6,
|
||||
additionalIps,
|
||||
dns: vps.dns,
|
||||
country: vps.country,
|
||||
city: vps.city,
|
||||
datacenter: vps.datacenter,
|
||||
os: vps.os,
|
||||
status: vps.status,
|
||||
tariffType: vps.tariffType,
|
||||
currency: vps.currency,
|
||||
dailyRate,
|
||||
monthlyRate,
|
||||
paidUntil,
|
||||
notes,
|
||||
}
|
||||
for (const f of SYNC_UPDATE_FIELDS) {
|
||||
if (userOverrides.includes(f)) {
|
||||
merged[f] = existing[f]
|
||||
}
|
||||
}
|
||||
const compareFields = ['ip', 'ipv6', 'dns', ...SYNC_UPDATE_FIELDS]
|
||||
const changedFields = compareFields.filter(
|
||||
(f) => normVal(merged[f]) !== normVal(existing[f]),
|
||||
)
|
||||
if (changedFields.length > 0) {
|
||||
const label = merged.dns || merged.ip || existing.id
|
||||
syncSummary.updated.push({ id: existing.id, label, fields: changedFields })
|
||||
}
|
||||
db.run(vpsUpdateSql,
|
||||
merged.ip,
|
||||
merged.ipv6,
|
||||
merged.additionalIps,
|
||||
merged.dns,
|
||||
merged.country,
|
||||
merged.city,
|
||||
merged.datacenter,
|
||||
merged.os,
|
||||
merged.status,
|
||||
merged.tariffType,
|
||||
merged.currency,
|
||||
merged.dailyRate,
|
||||
merged.monthlyRate,
|
||||
merged.paidUntil,
|
||||
merged.notes,
|
||||
existing.id,
|
||||
)
|
||||
} else {
|
||||
const label = vps.dns || vps.ip || id
|
||||
syncSummary.added.push({ id, label })
|
||||
db.run(vpsInsertSql,
|
||||
id,
|
||||
vps.ip,
|
||||
vps.ipv6,
|
||||
additionalIps,
|
||||
vps.dns,
|
||||
vps.providerId,
|
||||
vps.providerAccountId,
|
||||
vps.country,
|
||||
vps.city,
|
||||
vps.datacenter,
|
||||
vps.os,
|
||||
vps.vcpu,
|
||||
vps.ramGb,
|
||||
vps.diskGb,
|
||||
vps.diskType,
|
||||
vps.virtualization,
|
||||
vps.bandwidthTb,
|
||||
vps.sshPort,
|
||||
vps.rootUser,
|
||||
vps.purpose,
|
||||
vps.environment,
|
||||
vps.project,
|
||||
null,
|
||||
vps.monitoringEnabled ? 1 : 0,
|
||||
vps.backupEnabled ? 1 : 0,
|
||||
vps.status,
|
||||
vps.tariffType,
|
||||
vps.currency,
|
||||
dailyRate,
|
||||
monthlyRate,
|
||||
vps.createdAt,
|
||||
paidUntil,
|
||||
notes,
|
||||
'[]',
|
||||
)
|
||||
}
|
||||
vpsCount++
|
||||
}
|
||||
}
|
||||
|
||||
let paymentsCount = 0
|
||||
if (fetchVpsPayments) {
|
||||
const existingPayments = new Set(
|
||||
db.prepare('SELECT note FROM payments WHERE providerAccountId = ?').all(accountId).map((r) => r.note),
|
||||
)
|
||||
const paymentInsertSql = `INSERT INTO payments (id, type, date, amount, currency, providerAccountId, vpsId, note)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?)`
|
||||
|
||||
for (const item of paymentItems) {
|
||||
const payment = mapPaymentToPayment(item, accountId)
|
||||
if (!payment || payment.amount <= 0) continue
|
||||
const note = payment.note
|
||||
if (existingPayments.has(note)) continue
|
||||
const id = `pay-bm-${accountId}-${payment.externalId}`
|
||||
db.run(paymentInsertSql, id, payment.type, payment.date, payment.amount, payment.currency, payment.providerAccountId, payment.vpsId, note)
|
||||
existingPayments.add(note)
|
||||
paymentsCount++
|
||||
syncSummary.paymentsAdded += 1
|
||||
}
|
||||
}
|
||||
|
||||
if (fetchVpsPayments && dashboardInfo) {
|
||||
db.run(
|
||||
'UPDATE provider_accounts SET balance_api=?, balance_currency=?, balance_updated_at=?, enoughmoneyto=? WHERE id=?',
|
||||
dashboardInfo.balance,
|
||||
dashboardInfo.currency || 'RUB',
|
||||
new Date().toISOString(),
|
||||
dashboardInfo.enoughmoneyto || '',
|
||||
accountId,
|
||||
)
|
||||
}
|
||||
|
||||
let tariffsCount = 0
|
||||
let newTariffs = []
|
||||
if (fetchTariffs) {
|
||||
const existingTariffIds = new Set(
|
||||
db.prepare('SELECT id FROM active_tariffs WHERE providerAccountId = ?').all(accountId).map((r) => r.id),
|
||||
)
|
||||
const syncedAt = new Date().toISOString()
|
||||
db.run('DELETE FROM active_tariffs WHERE providerAccountId = ?', accountId)
|
||||
const tariffInsertSql = `INSERT INTO active_tariffs (id, providerAccountId, providerId, externalId, datacenterKey, datacenterName, name, desc, vcpu, ramGb, diskGb, diskType, virtualization, channel, location, country, cpuModel, orderAvailable, price, syncedAt)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`
|
||||
|
||||
for (const t of tariffItems) {
|
||||
const dcKey = t.datacenterKey ?? ''
|
||||
const dcName = t.datacenterName ?? ''
|
||||
const id = dcKey ? `tariff-bm-${accountId}-${t.externalId}-${dcKey}` : `tariff-bm-${accountId}-${t.externalId}`
|
||||
if (!existingTariffIds.has(id)) {
|
||||
newTariffs.push({ name: t.name || '', price: t.price || '', providerId })
|
||||
}
|
||||
db.run(tariffInsertSql,
|
||||
id,
|
||||
accountId,
|
||||
providerId,
|
||||
t.externalId,
|
||||
dcKey,
|
||||
dcName,
|
||||
t.name || '',
|
||||
t.desc || '',
|
||||
t.vcpu || 0,
|
||||
t.ramGb || 0,
|
||||
t.diskGb || 0,
|
||||
t.diskType || 'SSD',
|
||||
t.virtualization || 'KVM',
|
||||
t.channel || '',
|
||||
t.location || '',
|
||||
t.country || '',
|
||||
t.cpuModel || '',
|
||||
t.orderAvailable ? 1 : 0,
|
||||
t.price || '',
|
||||
syncedAt,
|
||||
)
|
||||
tariffsCount++
|
||||
}
|
||||
|
||||
if (Object.keys(slist).length > 0) {
|
||||
const datacenters = Array.isArray(slist.datacenter) ? JSON.stringify(slist.datacenter) : '[]'
|
||||
const periods = Array.isArray(slist.period) ? JSON.stringify(slist.period) : '[]'
|
||||
db.run(
|
||||
`INSERT OR REPLACE INTO tariff_sync_options (providerAccountId, datacenters, periods, syncedAt) VALUES (?, ?, ?, ?)`,
|
||||
accountId,
|
||||
datacenters,
|
||||
periods,
|
||||
syncedAt,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
if (!fetchVpsPayments) {
|
||||
syncSummary.tariffsOnly = true
|
||||
}
|
||||
return { vpsCount, paymentsCount, tariffsCount, newTariffs, balance: dashboardInfo, syncSummary }
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
/**
|
||||
* Re-export from db module
|
||||
*/
|
||||
export { initDb, getDb, saveDb, DB_PATH, reloadDatabaseFromBuffer } from './db/index.js'
|
||||
@@ -0,0 +1,139 @@
|
||||
/**
|
||||
* Database initialization and access
|
||||
*/
|
||||
|
||||
import initSqlJs from 'sql.js'
|
||||
import { readFileSync, writeFileSync, existsSync, mkdirSync } from 'fs'
|
||||
import { join, dirname } from 'path'
|
||||
import { fileURLToPath } from 'url'
|
||||
|
||||
import { SCHEMA } from './schema.js'
|
||||
import { MIGRATIONS } from './migrations.js'
|
||||
import { seed, isDbEmpty } from './seed.js'
|
||||
|
||||
const __dirname = dirname(fileURLToPath(import.meta.url))
|
||||
// db/ is in server/, so .. = server, .. again = project root
|
||||
export const DB_PATH = join(__dirname, '..', '..', 'data', 'vps-tracker.db')
|
||||
const SEED_DIR = join(__dirname, '..', '..', 'public', 'data')
|
||||
|
||||
let dbInstance = null
|
||||
/** @type {import('sql.js').SqlJsStatic | null} */
|
||||
let sqlJsFactory = null
|
||||
|
||||
export async function initDb() {
|
||||
const dataDir = join(__dirname, '..', '..', 'data')
|
||||
if (!existsSync(dataDir)) {
|
||||
mkdirSync(dataDir, { recursive: true })
|
||||
}
|
||||
|
||||
const SQL = await initSqlJs()
|
||||
sqlJsFactory = SQL
|
||||
let db
|
||||
|
||||
if (existsSync(DB_PATH)) {
|
||||
const fileBuffer = readFileSync(DB_PATH)
|
||||
db = new SQL.Database(fileBuffer)
|
||||
} else {
|
||||
db = new SQL.Database()
|
||||
}
|
||||
|
||||
db.exec(SCHEMA)
|
||||
|
||||
for (const m of MIGRATIONS) {
|
||||
try {
|
||||
m.run(db)
|
||||
} catch (err) {
|
||||
console.warn(`Migration ${m.name} failed:`, err.message)
|
||||
}
|
||||
}
|
||||
|
||||
if (isDbEmpty(db)) {
|
||||
seed(db, SEED_DIR)
|
||||
const data = db.export()
|
||||
writeFileSync(DB_PATH, Buffer.from(data))
|
||||
}
|
||||
|
||||
dbInstance = db
|
||||
if (existsSync(DB_PATH)) {
|
||||
saveDb()
|
||||
}
|
||||
return db
|
||||
}
|
||||
|
||||
export function getDb() {
|
||||
if (!dbInstance) throw new Error('Database not initialized')
|
||||
return createDbWrapper(dbInstance)
|
||||
}
|
||||
|
||||
function createDbWrapper(db) {
|
||||
return {
|
||||
/** One-off run: prepare, bind, step, free. Use for statements that run once. */
|
||||
run(sql, ...params) {
|
||||
const stmt = db.prepare(sql)
|
||||
stmt.bind(params)
|
||||
stmt.step()
|
||||
const changes = db.getRowsModified()
|
||||
stmt.free()
|
||||
saveDb()
|
||||
return { changes }
|
||||
},
|
||||
prepare(sql) {
|
||||
const stmt = db.prepare(sql)
|
||||
return {
|
||||
all(...params) {
|
||||
stmt.bind(params)
|
||||
const rows = []
|
||||
while (stmt.step()) {
|
||||
rows.push(stmt.getAsObject())
|
||||
}
|
||||
stmt.free()
|
||||
return rows
|
||||
},
|
||||
get(...params) {
|
||||
stmt.bind(params)
|
||||
const row = stmt.step() ? stmt.getAsObject() : null
|
||||
stmt.free()
|
||||
return row
|
||||
},
|
||||
run(...params) {
|
||||
stmt.bind(params)
|
||||
stmt.step()
|
||||
const changes = db.getRowsModified()
|
||||
stmt.free()
|
||||
saveDb()
|
||||
return { changes }
|
||||
},
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
export function saveDb() {
|
||||
if (!dbInstance) return
|
||||
const data = dbInstance.export()
|
||||
writeFileSync(DB_PATH, Buffer.from(data))
|
||||
}
|
||||
|
||||
/**
|
||||
* Заменить in-memory БД из буфера SQLite и сохранить на диск.
|
||||
* @param {Buffer|Uint8Array} buffer
|
||||
*/
|
||||
export async function reloadDatabaseFromBuffer(buffer) {
|
||||
const SQL = sqlJsFactory || (await initSqlJs())
|
||||
sqlJsFactory = SQL
|
||||
if (dbInstance) {
|
||||
dbInstance.close()
|
||||
dbInstance = null
|
||||
}
|
||||
const u8 = buffer instanceof Buffer ? new Uint8Array(buffer) : buffer
|
||||
dbInstance = new SQL.Database(u8)
|
||||
dbInstance.exec(SCHEMA)
|
||||
for (const m of MIGRATIONS) {
|
||||
try {
|
||||
m.run(dbInstance)
|
||||
} catch (err) {
|
||||
console.warn(`Migration ${m.name} after reload failed:`, err.message)
|
||||
}
|
||||
}
|
||||
saveDb()
|
||||
}
|
||||
@@ -0,0 +1,388 @@
|
||||
/**
|
||||
* Database migrations — add columns to existing tables
|
||||
*/
|
||||
|
||||
import { randomUUID } from 'node:crypto'
|
||||
|
||||
/**
|
||||
* Перенос apiType/apiBaseUrl с аккаунтов на хостера (idempotent).
|
||||
* Вызывается из миграции и после импорта бэкапа / старого migrate API.
|
||||
* @param {import('sql.js').Database} db
|
||||
*/
|
||||
function selectAllObjects(db, sql, params = []) {
|
||||
const prepared = db.prepare(sql)
|
||||
if (typeof prepared.all === 'function') {
|
||||
return prepared.all(...params)
|
||||
}
|
||||
const stmt = prepared
|
||||
stmt.bind(params)
|
||||
const rows = []
|
||||
while (stmt.step()) {
|
||||
rows.push(stmt.getAsObject())
|
||||
}
|
||||
stmt.free()
|
||||
return rows
|
||||
}
|
||||
|
||||
export function consolidateProviderApiFromAccounts(db) {
|
||||
const provRows = selectAllObjects(db, 'SELECT id, apiType, apiBaseUrl FROM providers')
|
||||
for (const prov of provRows) {
|
||||
const pid = prov.id
|
||||
if (String(prov.apiType || '').trim() || String(prov.apiBaseUrl || '').trim()) {
|
||||
continue
|
||||
}
|
||||
const accRows = selectAllObjects(
|
||||
db,
|
||||
`SELECT apiBaseUrl FROM provider_accounts
|
||||
WHERE providerId = ?
|
||||
AND length(trim(COALESCE(apiBaseUrl, ''))) > 0
|
||||
AND (
|
||||
lower(trim(COALESCE(apiType, ''))) = 'billmanager'
|
||||
OR instr(lower(trim(COALESCE(apiBaseUrl, ''))), 'billmgr') > 0
|
||||
)
|
||||
ORDER BY id`,
|
||||
[pid],
|
||||
)
|
||||
if (!accRows.length) continue
|
||||
const urls = [...new Set(accRows.map((r) => String(r.apiBaseUrl || '').trim()).filter(Boolean))]
|
||||
if (urls.length > 1) {
|
||||
console.warn(
|
||||
`[vps-tracker] У хостера ${pid} у нескольких аккаунтов разный URL BILLmanager — в настройках хостера взят первый.`,
|
||||
)
|
||||
}
|
||||
const apiBaseUrl = urls[0]
|
||||
db.run(`UPDATE providers SET apiType = ?, apiBaseUrl = ? WHERE id = ?`, 'billmanager', apiBaseUrl, pid)
|
||||
db.run(
|
||||
`UPDATE provider_accounts SET apiType = '', apiBaseUrl = ''
|
||||
WHERE providerId = ?
|
||||
AND length(trim(COALESCE(apiBaseUrl, ''))) > 0
|
||||
AND (
|
||||
lower(trim(COALESCE(apiType, ''))) = 'billmanager'
|
||||
OR instr(lower(trim(COALESCE(apiBaseUrl, ''))), 'billmgr') > 0
|
||||
)`,
|
||||
pid,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Раньше URL BILLmanager часто указывали в «Сайт» хостера или в panelUrl аккаунта, без apiType/apiBaseUrl.
|
||||
*/
|
||||
export function heuristicBillmanagerProviderApi(db) {
|
||||
const tryBillmgrUrl = (raw) => {
|
||||
const t = String(raw || '').trim()
|
||||
if (!t) return ''
|
||||
if (!/^https?:\/\//i.test(t)) return ''
|
||||
if (!/billmgr/i.test(t)) return ''
|
||||
return t.replace(/\/+$/, '')
|
||||
}
|
||||
|
||||
const provRows = selectAllObjects(db, 'SELECT id, website, apiType, apiBaseUrl FROM providers')
|
||||
for (const prov of provRows) {
|
||||
if (String(prov.apiType || '').trim() || String(prov.apiBaseUrl || '').trim()) continue
|
||||
|
||||
let url = tryBillmgrUrl(prov.website)
|
||||
if (!url) {
|
||||
const accRows = selectAllObjects(
|
||||
db,
|
||||
`SELECT panelUrl FROM provider_accounts
|
||||
WHERE providerId = ? AND length(trim(COALESCE(panelUrl, ''))) > 0
|
||||
ORDER BY id`,
|
||||
[prov.id],
|
||||
)
|
||||
for (const row of accRows) {
|
||||
url = tryBillmgrUrl(row.panelUrl)
|
||||
if (url) break
|
||||
}
|
||||
}
|
||||
if (url) {
|
||||
db.run(`UPDATE providers SET apiType = ?, apiBaseUrl = ? WHERE id = ?`, 'billmanager', url, prov.id)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Перенос API на хостера: с аккаунтов + эвристика по website/panelUrl. */
|
||||
export function consolidateAllProviderApiSources(db) {
|
||||
consolidateProviderApiFromAccounts(db)
|
||||
heuristicBillmanagerProviderApi(db)
|
||||
}
|
||||
|
||||
export const MIGRATIONS = [
|
||||
{
|
||||
name: 'provider_accounts_api',
|
||||
run(db) {
|
||||
try {
|
||||
db.exec('ALTER TABLE provider_accounts ADD COLUMN apiType TEXT')
|
||||
} catch (e) {
|
||||
if (!e.message?.includes('duplicate column')) throw e
|
||||
}
|
||||
try {
|
||||
db.exec('ALTER TABLE provider_accounts ADD COLUMN apiBaseUrl TEXT')
|
||||
} catch (e) {
|
||||
if (!e.message?.includes('duplicate column')) throw e
|
||||
}
|
||||
try {
|
||||
db.exec('ALTER TABLE provider_accounts ADD COLUMN apiCredentials TEXT')
|
||||
} catch (e) {
|
||||
if (!e.message?.includes('duplicate column')) throw e
|
||||
}
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'settings_sync',
|
||||
run(db) {
|
||||
try {
|
||||
db.exec('ALTER TABLE settings ADD COLUMN syncEnabled INTEGER')
|
||||
} catch (e) {
|
||||
if (!e.message?.includes('duplicate column')) throw e
|
||||
}
|
||||
try {
|
||||
db.exec('ALTER TABLE settings ADD COLUMN syncIntervalMinutes INTEGER')
|
||||
} catch (e) {
|
||||
if (!e.message?.includes('duplicate column')) throw e
|
||||
}
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'vps_paidUntil',
|
||||
run(db) {
|
||||
try {
|
||||
db.exec('ALTER TABLE vps ADD COLUMN paidUntil TEXT')
|
||||
} catch (e) {
|
||||
if (!e.message?.includes('duplicate column')) throw e
|
||||
}
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'provider_accounts_balance_api',
|
||||
run(db) {
|
||||
try {
|
||||
db.exec('ALTER TABLE provider_accounts ADD COLUMN balance_api REAL')
|
||||
} catch (e) {
|
||||
if (!e.message?.includes('duplicate column')) throw e
|
||||
}
|
||||
try {
|
||||
db.exec('ALTER TABLE provider_accounts ADD COLUMN balance_currency TEXT')
|
||||
} catch (e) {
|
||||
if (!e.message?.includes('duplicate column')) throw e
|
||||
}
|
||||
try {
|
||||
db.exec('ALTER TABLE provider_accounts ADD COLUMN balance_updated_at TEXT')
|
||||
} catch (e) {
|
||||
if (!e.message?.includes('duplicate column')) throw e
|
||||
}
|
||||
try {
|
||||
db.exec('ALTER TABLE provider_accounts ADD COLUMN enoughmoneyto TEXT')
|
||||
} catch (e) {
|
||||
if (!e.message?.includes('duplicate column')) throw e
|
||||
}
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'vps_userOverrides',
|
||||
run(db) {
|
||||
try {
|
||||
db.exec('ALTER TABLE vps ADD COLUMN userOverrides TEXT')
|
||||
} catch (e) {
|
||||
if (!e.message?.includes('duplicate column')) throw e
|
||||
}
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'active_tariffs_location_cpu',
|
||||
run(db) {
|
||||
try {
|
||||
db.exec('ALTER TABLE active_tariffs ADD COLUMN location TEXT')
|
||||
} catch (e) {
|
||||
if (!e.message?.includes('duplicate column')) throw e
|
||||
}
|
||||
try {
|
||||
db.exec('ALTER TABLE active_tariffs ADD COLUMN cpuModel TEXT')
|
||||
} catch (e) {
|
||||
if (!e.message?.includes('duplicate column')) throw e
|
||||
}
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'settings_customFields',
|
||||
run(db) {
|
||||
try {
|
||||
db.exec('ALTER TABLE settings ADD COLUMN customFields TEXT')
|
||||
} catch (e) {
|
||||
if (!e.message?.includes('duplicate column')) throw e
|
||||
}
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'settings_syncTariffsInterval',
|
||||
run(db) {
|
||||
try {
|
||||
db.exec('ALTER TABLE settings ADD COLUMN syncTariffsIntervalMinutes INTEGER')
|
||||
} catch (e) {
|
||||
if (!e.message?.includes('duplicate column')) throw e
|
||||
}
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'active_tariffs_country_datacenter',
|
||||
run(db) {
|
||||
try {
|
||||
db.exec('ALTER TABLE active_tariffs ADD COLUMN country TEXT')
|
||||
} catch (e) {
|
||||
if (!e.message?.includes('duplicate column')) throw e
|
||||
}
|
||||
try {
|
||||
db.exec('ALTER TABLE active_tariffs ADD COLUMN datacenterKey TEXT')
|
||||
} catch (e) {
|
||||
if (!e.message?.includes('duplicate column')) throw e
|
||||
}
|
||||
try {
|
||||
db.exec('ALTER TABLE active_tariffs ADD COLUMN datacenterName TEXT')
|
||||
} catch (e) {
|
||||
if (!e.message?.includes('duplicate column')) throw e
|
||||
}
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'settings_telegram',
|
||||
run(db) {
|
||||
try {
|
||||
db.exec('ALTER TABLE settings ADD COLUMN telegramBotToken TEXT')
|
||||
} catch (e) {
|
||||
if (!e.message?.includes('duplicate column')) throw e
|
||||
}
|
||||
try {
|
||||
db.exec('ALTER TABLE settings ADD COLUMN telegramChatId TEXT')
|
||||
} catch (e) {
|
||||
if (!e.message?.includes('duplicate column')) throw e
|
||||
}
|
||||
try {
|
||||
db.exec('ALTER TABLE settings ADD COLUMN notifyPaymentExpiryEnabled INTEGER')
|
||||
} catch (e) {
|
||||
if (!e.message?.includes('duplicate column')) throw e
|
||||
}
|
||||
try {
|
||||
db.exec('ALTER TABLE settings ADD COLUMN notifyNewTariffsEnabled INTEGER')
|
||||
} catch (e) {
|
||||
if (!e.message?.includes('duplicate column')) throw e
|
||||
}
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'settings_telegram_thread',
|
||||
run(db) {
|
||||
try {
|
||||
db.exec('ALTER TABLE settings ADD COLUMN telegramMessageThreadId TEXT')
|
||||
} catch (e) {
|
||||
if (!e.message?.includes('duplicate column')) throw e
|
||||
}
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'server_projects',
|
||||
run(db) {
|
||||
db.run(
|
||||
`CREATE TABLE IF NOT EXISTS server_projects (
|
||||
id TEXT PRIMARY KEY,
|
||||
name TEXT NOT NULL,
|
||||
color TEXT,
|
||||
sortOrder INTEGER DEFAULT 0,
|
||||
notes TEXT,
|
||||
createdAt TEXT
|
||||
)`,
|
||||
)
|
||||
try {
|
||||
db.run('ALTER TABLE vps ADD COLUMN projectId TEXT')
|
||||
} catch (e) {
|
||||
if (!String(e.message || e).includes('duplicate column')) throw e
|
||||
}
|
||||
|
||||
const distinctStmt = db.prepare(
|
||||
`SELECT DISTINCT trim(project) AS n FROM vps WHERE length(trim(COALESCE(project, ''))) > 0`,
|
||||
)
|
||||
const seenLower = new Set()
|
||||
const findStmt = db.prepare(
|
||||
'SELECT id FROM server_projects WHERE LOWER(name) = LOWER(?) LIMIT 1',
|
||||
)
|
||||
while (distinctStmt.step()) {
|
||||
const row = distinctStmt.getAsObject()
|
||||
const t = String(row.n ?? '').trim()
|
||||
if (!t) continue
|
||||
const lk = t.toLowerCase()
|
||||
if (seenLower.has(lk)) continue
|
||||
seenLower.add(lk)
|
||||
|
||||
findStmt.bind([t])
|
||||
const exists = Boolean(findStmt.step())
|
||||
findStmt.reset()
|
||||
if (!exists) {
|
||||
const id = `proj-${randomUUID()}`
|
||||
const now = new Date().toISOString()
|
||||
db.run(
|
||||
`INSERT INTO server_projects (id, name, color, sortOrder, notes, createdAt) VALUES (?, ?, NULL, 0, NULL, ?)`,
|
||||
[id, t, now],
|
||||
)
|
||||
}
|
||||
}
|
||||
distinctStmt.free()
|
||||
findStmt.free()
|
||||
|
||||
db.run(`UPDATE vps SET projectId = (
|
||||
SELECT sp.id FROM server_projects sp
|
||||
WHERE LOWER(sp.name) = LOWER(trim(COALESCE(vps.project, '')))
|
||||
LIMIT 1
|
||||
) WHERE length(trim(COALESCE(vps.project, ''))) > 0`)
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'sync_log_summary',
|
||||
run(db) {
|
||||
try {
|
||||
db.exec('ALTER TABLE sync_log ADD COLUMN summary TEXT')
|
||||
} catch (e) {
|
||||
if (!String(e.message || e).includes('duplicate column')) throw e
|
||||
}
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'settings_notify_balance_digest',
|
||||
run(db) {
|
||||
try {
|
||||
db.exec('ALTER TABLE settings ADD COLUMN notifyLowBalanceEnabled INTEGER')
|
||||
} catch (e) {
|
||||
if (!String(e.message || e).includes('duplicate column')) throw e
|
||||
}
|
||||
try {
|
||||
db.exec('ALTER TABLE settings ADD COLUMN notifySyncDigestEnabled INTEGER')
|
||||
} catch (e) {
|
||||
if (!String(e.message || e).includes('duplicate column')) throw e
|
||||
}
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'provider_accounts_balance_alert_below',
|
||||
run(db) {
|
||||
try {
|
||||
db.exec('ALTER TABLE provider_accounts ADD COLUMN balance_alert_below REAL')
|
||||
} catch (e) {
|
||||
if (!String(e.message || e).includes('duplicate column')) throw e
|
||||
}
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'providers_api_integration',
|
||||
run(db) {
|
||||
try {
|
||||
db.exec('ALTER TABLE providers ADD COLUMN apiType TEXT')
|
||||
} catch (e) {
|
||||
if (!String(e.message || e).includes('duplicate column')) throw e
|
||||
}
|
||||
try {
|
||||
db.exec('ALTER TABLE providers ADD COLUMN apiBaseUrl TEXT')
|
||||
} catch (e) {
|
||||
if (!String(e.message || e).includes('duplicate column')) throw e
|
||||
}
|
||||
consolidateAllProviderApiSources(db)
|
||||
},
|
||||
},
|
||||
]
|
||||
@@ -0,0 +1,165 @@
|
||||
/**
|
||||
* SQLite schema for vps-tracker
|
||||
*/
|
||||
|
||||
export const SCHEMA = `
|
||||
CREATE TABLE IF NOT EXISTS providers (
|
||||
id TEXT PRIMARY KEY,
|
||||
name TEXT NOT NULL,
|
||||
website TEXT,
|
||||
contact TEXT,
|
||||
baseCurrency TEXT,
|
||||
usdRate TEXT,
|
||||
eurRate TEXT,
|
||||
notes TEXT,
|
||||
apiType TEXT,
|
||||
apiBaseUrl TEXT
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS provider_accounts (
|
||||
id TEXT PRIMARY KEY,
|
||||
providerId TEXT NOT NULL,
|
||||
name TEXT NOT NULL,
|
||||
panelUrl TEXT,
|
||||
currency TEXT,
|
||||
billingMode TEXT,
|
||||
notes TEXT,
|
||||
apiType TEXT,
|
||||
apiBaseUrl TEXT,
|
||||
apiCredentials TEXT,
|
||||
FOREIGN KEY (providerId) REFERENCES providers(id)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS server_projects (
|
||||
id TEXT PRIMARY KEY,
|
||||
name TEXT NOT NULL,
|
||||
color TEXT,
|
||||
sortOrder INTEGER DEFAULT 0,
|
||||
notes TEXT,
|
||||
createdAt TEXT
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS vps (
|
||||
id TEXT PRIMARY KEY,
|
||||
ip TEXT,
|
||||
ipv6 TEXT,
|
||||
additionalIps TEXT,
|
||||
dns TEXT,
|
||||
providerId TEXT,
|
||||
providerAccountId TEXT,
|
||||
country TEXT,
|
||||
city TEXT,
|
||||
datacenter TEXT,
|
||||
os TEXT,
|
||||
vcpu INTEGER,
|
||||
ramGb INTEGER,
|
||||
diskGb INTEGER,
|
||||
diskType TEXT,
|
||||
virtualization TEXT,
|
||||
bandwidthTb INTEGER,
|
||||
sshPort INTEGER,
|
||||
rootUser TEXT,
|
||||
purpose TEXT,
|
||||
environment TEXT,
|
||||
project TEXT,
|
||||
projectId TEXT,
|
||||
monitoringEnabled INTEGER,
|
||||
backupEnabled INTEGER,
|
||||
status TEXT,
|
||||
tariffType TEXT,
|
||||
currency TEXT,
|
||||
dailyRate REAL,
|
||||
monthlyRate REAL,
|
||||
createdAt TEXT,
|
||||
paidUntil TEXT,
|
||||
notes TEXT,
|
||||
userOverrides TEXT,
|
||||
FOREIGN KEY (providerId) REFERENCES providers(id),
|
||||
FOREIGN KEY (providerAccountId) REFERENCES provider_accounts(id),
|
||||
FOREIGN KEY (projectId) REFERENCES server_projects(id)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS payments (
|
||||
id TEXT PRIMARY KEY,
|
||||
type TEXT NOT NULL,
|
||||
date TEXT NOT NULL,
|
||||
amount REAL NOT NULL,
|
||||
currency TEXT,
|
||||
providerAccountId TEXT,
|
||||
vpsId TEXT,
|
||||
note TEXT,
|
||||
FOREIGN KEY (providerAccountId) REFERENCES provider_accounts(id),
|
||||
FOREIGN KEY (vpsId) REFERENCES vps(id)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS balance_ledger (
|
||||
id TEXT PRIMARY KEY,
|
||||
type TEXT NOT NULL,
|
||||
date TEXT NOT NULL,
|
||||
amount REAL NOT NULL,
|
||||
currency TEXT,
|
||||
direction TEXT,
|
||||
providerAccountId TEXT,
|
||||
vpsId TEXT,
|
||||
note TEXT,
|
||||
FOREIGN KEY (providerAccountId) REFERENCES provider_accounts(id),
|
||||
FOREIGN KEY (vpsId) REFERENCES vps(id)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS settings (
|
||||
id TEXT PRIMARY KEY,
|
||||
baseCurrency TEXT,
|
||||
ratesUrl TEXT,
|
||||
autoConvert INTEGER,
|
||||
ratesUpdatedAt TEXT,
|
||||
syncEnabled INTEGER,
|
||||
syncIntervalMinutes INTEGER,
|
||||
syncTariffsIntervalMinutes INTEGER,
|
||||
customFields TEXT
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS sync_log (
|
||||
id TEXT PRIMARY KEY,
|
||||
accountId TEXT NOT NULL,
|
||||
startedAt TEXT NOT NULL,
|
||||
finishedAt TEXT,
|
||||
status TEXT,
|
||||
vpsCount INTEGER,
|
||||
paymentsCount INTEGER,
|
||||
error TEXT,
|
||||
FOREIGN KEY (accountId) REFERENCES provider_accounts(id)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS active_tariffs (
|
||||
id TEXT PRIMARY KEY,
|
||||
providerAccountId TEXT NOT NULL,
|
||||
providerId TEXT NOT NULL,
|
||||
externalId TEXT NOT NULL,
|
||||
datacenterKey TEXT,
|
||||
datacenterName TEXT,
|
||||
name TEXT,
|
||||
desc TEXT,
|
||||
vcpu INTEGER,
|
||||
ramGb REAL,
|
||||
diskGb INTEGER,
|
||||
diskType TEXT,
|
||||
virtualization TEXT,
|
||||
channel TEXT,
|
||||
location TEXT,
|
||||
country TEXT,
|
||||
cpuModel TEXT,
|
||||
orderAvailable INTEGER,
|
||||
price TEXT,
|
||||
syncedAt TEXT,
|
||||
FOREIGN KEY (providerAccountId) REFERENCES provider_accounts(id),
|
||||
FOREIGN KEY (providerId) REFERENCES providers(id)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS tariff_sync_options (
|
||||
providerAccountId TEXT PRIMARY KEY,
|
||||
datacenters TEXT,
|
||||
periods TEXT,
|
||||
syncedAt TEXT,
|
||||
FOREIGN KEY (providerAccountId) REFERENCES provider_accounts(id)
|
||||
);
|
||||
`
|
||||
@@ -0,0 +1,146 @@
|
||||
/**
|
||||
* Seed database with initial data from public/data/*.json
|
||||
*/
|
||||
|
||||
import { readFileSync, existsSync } from 'fs'
|
||||
import { join } from 'path'
|
||||
|
||||
/**
|
||||
* @param {string} path - path to JSON file
|
||||
* @returns {Array}
|
||||
*/
|
||||
function loadJson(path) {
|
||||
if (!existsSync(path)) return []
|
||||
const raw = readFileSync(path, 'utf-8')
|
||||
try {
|
||||
const data = JSON.parse(raw)
|
||||
return Array.isArray(data) ? data : [data]
|
||||
} catch {
|
||||
return []
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {object} db - raw sql.js database (not wrapper)
|
||||
* @param {string} seedDir - path to public/data
|
||||
*/
|
||||
export function seed(db, seedDir) {
|
||||
const providers = loadJson(join(seedDir, 'providers.json'))
|
||||
if (providers.length === 0) return
|
||||
|
||||
const run = db.run.bind(db)
|
||||
for (const r of providers) {
|
||||
run(
|
||||
'INSERT OR IGNORE INTO providers (id, name, website, contact, baseCurrency, usdRate, eurRate, notes, apiType, apiBaseUrl) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)',
|
||||
[
|
||||
r.id,
|
||||
r.name ?? '',
|
||||
r.website ?? '',
|
||||
r.contact ?? '',
|
||||
r.baseCurrency ?? '',
|
||||
r.usdRate ?? '',
|
||||
r.eurRate ?? '',
|
||||
r.notes ?? '',
|
||||
r.apiType ?? '',
|
||||
r.apiBaseUrl ?? '',
|
||||
],
|
||||
)
|
||||
}
|
||||
|
||||
const providerAccounts = loadJson(join(seedDir, 'provider-accounts.json'))
|
||||
for (const r of providerAccounts) {
|
||||
const legacyType = r.apiType ?? ''
|
||||
const legacyUrl = r.apiBaseUrl ?? ''
|
||||
run(
|
||||
'INSERT OR IGNORE INTO provider_accounts (id, providerId, name, panelUrl, currency, billingMode, notes, apiType, apiBaseUrl, apiCredentials) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)',
|
||||
[r.id, r.providerId ?? '', r.name ?? '', r.panelUrl ?? '', r.currency ?? '', r.billingMode ?? '', r.notes ?? '', '', '', r.apiCredentials ?? ''],
|
||||
)
|
||||
if (legacyType === 'billmanager' && String(legacyUrl).trim()) {
|
||||
run(
|
||||
`UPDATE providers SET apiType = 'billmanager', apiBaseUrl = ? WHERE id = ? AND length(trim(COALESCE(apiBaseUrl,''))) = 0`,
|
||||
String(legacyUrl).trim(),
|
||||
r.providerId ?? '',
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
const vpsList = loadJson(join(seedDir, 'vps.json'))
|
||||
for (const r of vpsList) {
|
||||
const additionalIps = Array.isArray(r.additionalIps) ? JSON.stringify(r.additionalIps) : '[]'
|
||||
const dailyRate = r.dailyRate === '' || r.dailyRate == null ? null : Number(r.dailyRate)
|
||||
const monthlyRate = r.monthlyRate === '' || r.monthlyRate == null ? null : Number(r.monthlyRate)
|
||||
run(
|
||||
`INSERT OR IGNORE INTO vps (id, ip, ipv6, additionalIps, dns, providerId, providerAccountId, country, city, datacenter, os, vcpu, ramGb, diskGb, diskType, virtualization, bandwidthTb, sshPort, rootUser, purpose, environment, project, projectId, monitoringEnabled, backupEnabled, status, tariffType, currency, dailyRate, monthlyRate, createdAt, paidUntil, notes, userOverrides) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
|
||||
[
|
||||
r.id,
|
||||
r.ip ?? '',
|
||||
r.ipv6 ?? '',
|
||||
additionalIps,
|
||||
r.dns ?? '',
|
||||
r.providerId ?? '',
|
||||
r.providerAccountId ?? '',
|
||||
r.country ?? '',
|
||||
r.city ?? '',
|
||||
r.datacenter ?? '',
|
||||
r.os ?? '',
|
||||
r.vcpu ?? 0,
|
||||
r.ramGb ?? 0,
|
||||
r.diskGb ?? 0,
|
||||
r.diskType ?? '',
|
||||
r.virtualization ?? '',
|
||||
r.bandwidthTb ?? 0,
|
||||
r.sshPort ?? 22,
|
||||
r.rootUser ?? '',
|
||||
r.purpose ?? '',
|
||||
r.environment ?? '',
|
||||
r.project ?? '',
|
||||
r.projectId ?? null,
|
||||
r.monitoringEnabled ? 1 : 0,
|
||||
r.backupEnabled ? 1 : 0,
|
||||
r.status ?? 'active',
|
||||
r.tariffType ?? '',
|
||||
r.currency ?? '',
|
||||
dailyRate,
|
||||
monthlyRate,
|
||||
r.createdAt ?? '',
|
||||
r.paidUntil ?? '',
|
||||
r.notes ?? '',
|
||||
'[]',
|
||||
],
|
||||
)
|
||||
}
|
||||
|
||||
const payments = loadJson(join(seedDir, 'payments.json'))
|
||||
for (const r of payments) {
|
||||
run(
|
||||
'INSERT OR IGNORE INTO payments (id, type, date, amount, currency, providerAccountId, vpsId, note) VALUES (?, ?, ?, ?, ?, ?, ?, ?)',
|
||||
[r.id, r.type ?? '', r.date ?? '', Number(r.amount) || 0, r.currency ?? '', r.providerAccountId ?? '', r.vpsId ?? '', r.note ?? ''],
|
||||
)
|
||||
}
|
||||
|
||||
const ledger = loadJson(join(seedDir, 'balance-ledger.json'))
|
||||
for (const r of ledger) {
|
||||
run(
|
||||
'INSERT OR IGNORE INTO balance_ledger (id, type, date, amount, currency, direction, providerAccountId, vpsId, note) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)',
|
||||
[r.id, r.type ?? '', r.date ?? '', Number(r.amount) || 0, r.currency ?? '', r.direction ?? '', r.providerAccountId ?? '', r.vpsId ?? '', r.note ?? ''],
|
||||
)
|
||||
}
|
||||
|
||||
const settingsList = loadJson(join(seedDir, 'settings.json'))
|
||||
for (const r of settingsList) {
|
||||
run(
|
||||
'INSERT OR IGNORE INTO settings (id, baseCurrency, ratesUrl, autoConvert, ratesUpdatedAt, syncEnabled, syncIntervalMinutes) VALUES (?, ?, ?, ?, ?, ?, ?)',
|
||||
[r.id ?? 'settings-main', r.baseCurrency ?? 'RUB', r.ratesUrl ?? '', r.autoConvert !== false ? 1 : 0, r.ratesUpdatedAt ?? '', r.syncEnabled ? 1 : 0, r.syncIntervalMinutes ?? 60],
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {object} db - raw sql.js database
|
||||
* @returns {boolean}
|
||||
*/
|
||||
export function isDbEmpty(db) {
|
||||
const result = db.exec('SELECT COUNT(*) as c FROM providers')
|
||||
if (!result.length || !result[0].values.length) return true
|
||||
return result[0].values[0][0] === 0
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
import express from 'express'
|
||||
import cors from 'cors'
|
||||
import { existsSync } from 'fs'
|
||||
import { dirname, join } from 'path'
|
||||
import { fileURLToPath } from 'url'
|
||||
import { initDb } from './db.js'
|
||||
|
||||
const __dirname = dirname(fileURLToPath(import.meta.url))
|
||||
const distPath = join(__dirname, '..', 'dist')
|
||||
import dataRouter from './routes/data.js'
|
||||
import migrateRouter from './routes/migrate.js'
|
||||
import vpsRouter from './routes/vps.js'
|
||||
import providersRouter from './routes/providers.js'
|
||||
import providerAccountsRouter from './routes/provider-accounts.js'
|
||||
import paymentsRouter from './routes/payments.js'
|
||||
import balanceLedgerRouter from './routes/balance-ledger.js'
|
||||
import settingsRouter from './routes/settings.js'
|
||||
import syncRouter from './routes/sync.js'
|
||||
import projectsRouter from './routes/projects.js'
|
||||
import backupRouter from './routes/backup.js'
|
||||
import ratesProxyRouter from './routes/rates-proxy.js'
|
||||
|
||||
const app = express()
|
||||
const PORT = process.env.PORT || 3001
|
||||
|
||||
app.use(cors())
|
||||
app.use(express.json({ limit: '50mb' }))
|
||||
|
||||
;(async () => {
|
||||
await initDb()
|
||||
|
||||
app.use('/api/data', dataRouter)
|
||||
app.use('/api/migrate', migrateRouter)
|
||||
app.use('/api/vps', vpsRouter)
|
||||
app.use('/api/providers', providersRouter)
|
||||
app.use('/api/provider-accounts', providerAccountsRouter)
|
||||
app.use('/api/payments', paymentsRouter)
|
||||
app.use('/api/balance-ledger', balanceLedgerRouter)
|
||||
app.use('/api/settings', settingsRouter)
|
||||
app.use('/api/sync', syncRouter)
|
||||
app.use('/api/projects', projectsRouter)
|
||||
app.use('/api/backup', backupRouter)
|
||||
app.use('/api/rates-proxy', ratesProxyRouter)
|
||||
|
||||
if (existsSync(distPath)) {
|
||||
app.use(express.static(distPath))
|
||||
app.get(/.*/, (req, res, next) => {
|
||||
if (req.path.startsWith('/api')) return next()
|
||||
res.sendFile(join(distPath, 'index.html'), (err) => (err ? next(err) : undefined))
|
||||
})
|
||||
}
|
||||
|
||||
const { startScheduler } = await import('./sync-scheduler.js')
|
||||
startScheduler()
|
||||
|
||||
app.listen(PORT, () => {
|
||||
console.log(`Server running at http://localhost:${PORT}`)
|
||||
})
|
||||
})()
|
||||
@@ -0,0 +1,35 @@
|
||||
{
|
||||
"name": "@cfdm/api",
|
||||
"private": true,
|
||||
"version": "0.0.0",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "tsx watch src/index.ts",
|
||||
"dev:legacy": "node index.js",
|
||||
"build": "tsc -p tsconfig.json",
|
||||
"start": "node dist/index.js",
|
||||
"start:legacy": "node index.js",
|
||||
"test": "vitest run"
|
||||
},
|
||||
"dependencies": {
|
||||
"@cfdm/db": "workspace:*",
|
||||
"@cfdm/shared": "workspace:*",
|
||||
"@fastify/cors": "^11.0.1",
|
||||
"@fastify/sensible": "^6.0.3",
|
||||
"@fastify/static": "^8.2.0",
|
||||
"fastify": "^5.6.1",
|
||||
"better-sqlite3": "^11.10.0",
|
||||
"drizzle-orm": "^0.40.0",
|
||||
"express": "^4.21.1",
|
||||
"cors": "^2.8.5",
|
||||
"sql.js": "^1.14.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^22.10.0",
|
||||
"@types/express": "^5.0.0",
|
||||
"@types/cors": "^2.8.17",
|
||||
"tsx": "^4.19.0",
|
||||
"typescript": "^5.9.2",
|
||||
"vitest": "^3.0.0"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
/**
|
||||
* Справочник проектов (пулов): поиск без учёта регистра, автосоздание, подсказки.
|
||||
*/
|
||||
|
||||
import { randomUUID } from 'node:crypto'
|
||||
|
||||
/**
|
||||
* @param {unknown} name
|
||||
* @returns {string}
|
||||
*/
|
||||
export function normalizeProjectNameInput(name) {
|
||||
if (name == null) return ''
|
||||
return String(name).trim()
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {ReturnType<import('./db.js').getDb>} db
|
||||
* @param {string} name — уже нормализованное имя (trim)
|
||||
* @returns {{ id: string, name: string, color?: string, sortOrder?: number, notes?: string, createdAt?: string } | null}
|
||||
*/
|
||||
export function findProjectByNameCaseInsensitive(db, name) {
|
||||
const n = normalizeProjectNameInput(name)
|
||||
if (!n) return null
|
||||
return db
|
||||
.prepare(
|
||||
`SELECT * FROM server_projects WHERE LOWER(name) = LOWER(?) LIMIT 1`,
|
||||
)
|
||||
.get(n)
|
||||
}
|
||||
|
||||
/**
|
||||
* Найти существующий проект или создать новую строку.
|
||||
* @param {ReturnType<import('./db.js').getDb>} db
|
||||
* @param {string} name
|
||||
* @returns {{ id: string | null, name: string }}
|
||||
*/
|
||||
export function resolveOrCreateProject(db, name) {
|
||||
const n = normalizeProjectNameInput(name)
|
||||
if (!n) return { id: null, name: '' }
|
||||
const existing = findProjectByNameCaseInsensitive(db, n)
|
||||
if (existing) {
|
||||
return { id: existing.id, name: existing.name }
|
||||
}
|
||||
const id = `proj-${randomUUID()}`
|
||||
const now = new Date().toISOString()
|
||||
db.prepare(
|
||||
`INSERT INTO server_projects (id, name, color, sortOrder, notes, createdAt) VALUES (?, ?, ?, 0, ?, ?)`,
|
||||
).run(id, n, null, null, now)
|
||||
return { id, name: n }
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {ReturnType<import('./db.js').getDb>} db
|
||||
* @param {string} q
|
||||
* @param {number} limit
|
||||
* @returns {{ id: string, name: string }[]}
|
||||
*/
|
||||
export function projectSuggestions(db, q, limit = 20) {
|
||||
const term = normalizeProjectNameInput(q)
|
||||
const lim = Math.min(50, Math.max(1, Number(limit) || 20))
|
||||
if (!term) {
|
||||
return db
|
||||
.prepare(`SELECT id, name FROM server_projects ORDER BY name LIMIT ?`)
|
||||
.all(lim)
|
||||
}
|
||||
const esc = term.replace(/\\/g, '\\\\').replace(/%/g, '\\%').replace(/_/g, '\\_')
|
||||
const pattern = `%${esc.toLowerCase()}%`
|
||||
return db
|
||||
.prepare(
|
||||
`SELECT id, name FROM server_projects WHERE LOWER(name) LIKE ? ESCAPE '\\' ORDER BY name LIMIT ?`,
|
||||
)
|
||||
.all(pattern, lim)
|
||||
}
|
||||
@@ -0,0 +1,348 @@
|
||||
import { Router } from 'express'
|
||||
import express from 'express'
|
||||
import { readFileSync, existsSync } from 'node:fs'
|
||||
import { getDb, saveDb, DB_PATH, reloadDatabaseFromBuffer } from '../db.js'
|
||||
import { consolidateAllProviderApiSources } from '../db/migrations.js'
|
||||
import { rowToVps } from './vps.js'
|
||||
import { rowToActiveTariff, rowToTariffSyncOptions } from '../utils/row-mappers.js'
|
||||
|
||||
const router = Router()
|
||||
const BACKUP_VERSION = 1
|
||||
|
||||
function buildJsonSnapshot() {
|
||||
saveDb()
|
||||
const db = getDb()
|
||||
const vps = db.prepare('SELECT * FROM vps ORDER BY createdAt DESC').all()
|
||||
const providers = db.prepare('SELECT * FROM providers ORDER BY name').all()
|
||||
const providerAccounts = db.prepare('SELECT * FROM provider_accounts ORDER BY name').all()
|
||||
const payments = db.prepare('SELECT * FROM payments ORDER BY date DESC').all()
|
||||
const balanceLedger = db.prepare('SELECT * FROM balance_ledger ORDER BY date DESC').all()
|
||||
const settingsRows = db.prepare('SELECT * FROM settings ORDER BY id').all()
|
||||
const activeTariffs = db.prepare('SELECT * FROM active_tariffs ORDER BY name').all()
|
||||
const tariffSyncOptions = db.prepare('SELECT * FROM tariff_sync_options').all()
|
||||
let serverProjects = []
|
||||
try {
|
||||
serverProjects = db
|
||||
.prepare('SELECT id, name, color, sortOrder, notes, createdAt FROM server_projects ORDER BY name')
|
||||
.all()
|
||||
} catch {
|
||||
serverProjects = []
|
||||
}
|
||||
let syncLog = []
|
||||
try {
|
||||
syncLog = db.prepare('SELECT * FROM sync_log ORDER BY startedAt DESC LIMIT 500').all()
|
||||
} catch {
|
||||
syncLog = []
|
||||
}
|
||||
|
||||
return {
|
||||
backupVersion: BACKUP_VERSION,
|
||||
exportedAt: new Date().toISOString(),
|
||||
vps: vps.map(rowToVps),
|
||||
serverProjects,
|
||||
providers,
|
||||
providerAccounts,
|
||||
payments,
|
||||
balanceLedger,
|
||||
settings: settingsRows,
|
||||
activeTariffs: activeTariffs.map(rowToActiveTariff),
|
||||
tariffSyncOptions: tariffSyncOptions.map(rowToTariffSyncOptions),
|
||||
syncLog,
|
||||
}
|
||||
}
|
||||
|
||||
router.get('/json', (req, res) => {
|
||||
try {
|
||||
const snapshot = buildJsonSnapshot()
|
||||
res.setHeader('Content-Type', 'application/json; charset=utf-8')
|
||||
res.setHeader('Content-Disposition', 'attachment; filename="vps-tracker-backup.json"')
|
||||
res.send(JSON.stringify(snapshot, null, 2))
|
||||
} catch (err) {
|
||||
res.status(500).json({ error: err.message })
|
||||
}
|
||||
})
|
||||
|
||||
router.get('/database', (req, res) => {
|
||||
try {
|
||||
saveDb()
|
||||
if (!existsSync(DB_PATH)) {
|
||||
return res.status(404).json({ error: 'Файл базы не найден' })
|
||||
}
|
||||
const buf = readFileSync(DB_PATH)
|
||||
res.setHeader('Content-Type', 'application/octet-stream')
|
||||
res.setHeader('Content-Disposition', 'attachment; filename="vps-tracker.db"')
|
||||
res.send(buf)
|
||||
} catch (err) {
|
||||
res.status(500).json({ error: err.message })
|
||||
}
|
||||
})
|
||||
|
||||
router.post('/json', (req, res) => {
|
||||
try {
|
||||
const payload = req.body
|
||||
if (!payload || typeof payload !== 'object') {
|
||||
return res.status(400).json({ error: 'Неверное тело запроса' })
|
||||
}
|
||||
importJsonSnapshot(payload)
|
||||
res.json({ ok: true })
|
||||
} catch (err) {
|
||||
console.error('Backup JSON import error:', err)
|
||||
res.status(500).json({ error: err.message || 'Импорт не удался' })
|
||||
}
|
||||
})
|
||||
|
||||
/**
|
||||
* @param {object} data
|
||||
*/
|
||||
function importJsonSnapshot(data) {
|
||||
const db = getDb()
|
||||
const run = (sql, ...params) => db.prepare(sql).run(...params)
|
||||
|
||||
run('DELETE FROM sync_log')
|
||||
run('DELETE FROM tariff_sync_options')
|
||||
run('DELETE FROM active_tariffs')
|
||||
run('DELETE FROM balance_ledger')
|
||||
run('DELETE FROM payments')
|
||||
run('DELETE FROM vps')
|
||||
run('DELETE FROM provider_accounts')
|
||||
run('DELETE FROM server_projects')
|
||||
run('DELETE FROM providers')
|
||||
run('DELETE FROM settings')
|
||||
|
||||
const providers = Array.isArray(data.providers) ? data.providers : []
|
||||
for (const p of providers) {
|
||||
run(
|
||||
`INSERT OR REPLACE INTO providers (id, name, website, contact, baseCurrency, usdRate, eurRate, notes, apiType, apiBaseUrl) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
|
||||
p.id ?? '',
|
||||
p.name ?? '',
|
||||
p.website ?? '',
|
||||
p.contact ?? '',
|
||||
p.baseCurrency ?? '',
|
||||
p.usdRate ?? '',
|
||||
p.eurRate ?? '',
|
||||
p.notes ?? '',
|
||||
p.apiType ?? '',
|
||||
p.apiBaseUrl ?? '',
|
||||
)
|
||||
}
|
||||
|
||||
const projects = Array.isArray(data.serverProjects) ? data.serverProjects : []
|
||||
for (const sp of projects) {
|
||||
run(
|
||||
`INSERT OR REPLACE INTO server_projects (id, name, color, sortOrder, notes, createdAt) VALUES (?, ?, ?, ?, ?, ?)`,
|
||||
sp.id ?? '',
|
||||
sp.name ?? '',
|
||||
sp.color ?? null,
|
||||
sp.sortOrder ?? 0,
|
||||
sp.notes ?? null,
|
||||
sp.createdAt ?? null,
|
||||
)
|
||||
}
|
||||
|
||||
const accounts = Array.isArray(data.providerAccounts) ? data.providerAccounts : []
|
||||
for (const acc of accounts) {
|
||||
run(
|
||||
`INSERT OR REPLACE INTO provider_accounts (id, providerId, name, panelUrl, currency, billingMode, notes, apiType, apiBaseUrl, apiCredentials, balance_api, balance_currency, balance_updated_at, enoughmoneyto, balance_alert_below)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
|
||||
acc.id ?? '',
|
||||
acc.providerId ?? '',
|
||||
acc.name ?? '',
|
||||
acc.panelUrl ?? '',
|
||||
acc.currency ?? '',
|
||||
acc.billingMode ?? '',
|
||||
acc.notes ?? '',
|
||||
acc.apiType ?? '',
|
||||
acc.apiBaseUrl ?? '',
|
||||
acc.apiCredentials ?? '',
|
||||
acc.balance_api ?? null,
|
||||
acc.balance_currency ?? null,
|
||||
acc.balance_updated_at ?? null,
|
||||
acc.enoughmoneyto ?? null,
|
||||
acc.balance_alert_below != null && acc.balance_alert_below !== '' ? Number(acc.balance_alert_below) : null,
|
||||
)
|
||||
}
|
||||
|
||||
consolidateAllProviderApiSources(db)
|
||||
|
||||
const settingsList = Array.isArray(data.settings) ? data.settings : data.settings ? [data.settings] : []
|
||||
for (const s of settingsList) {
|
||||
let customFields = s.customFields
|
||||
if (Array.isArray(customFields)) customFields = JSON.stringify(customFields)
|
||||
if (customFields === undefined) customFields = null
|
||||
run(
|
||||
`INSERT OR REPLACE INTO settings (id, baseCurrency, ratesUrl, autoConvert, ratesUpdatedAt, syncEnabled, syncIntervalMinutes, syncTariffsIntervalMinutes, telegramBotToken, telegramChatId, telegramMessageThreadId, notifyPaymentExpiryEnabled, notifyNewTariffsEnabled, customFields, notifyLowBalanceEnabled, notifySyncDigestEnabled)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
|
||||
s.id ?? 'settings-main',
|
||||
s.baseCurrency ?? 'RUB',
|
||||
s.ratesUrl ?? '',
|
||||
s.autoConvert !== false && s.autoConvert !== 0 ? 1 : 0,
|
||||
s.ratesUpdatedAt ?? '',
|
||||
s.syncEnabled ? 1 : 0,
|
||||
s.syncIntervalMinutes ?? 60,
|
||||
s.syncTariffsIntervalMinutes ?? 1440,
|
||||
s.telegramBotToken ?? '',
|
||||
s.telegramChatId ?? '',
|
||||
s.telegramMessageThreadId ?? '',
|
||||
s.notifyPaymentExpiryEnabled ? 1 : 0,
|
||||
s.notifyNewTariffsEnabled ? 1 : 0,
|
||||
customFields,
|
||||
s.notifyLowBalanceEnabled ? 1 : 0,
|
||||
s.notifySyncDigestEnabled ? 1 : 0,
|
||||
)
|
||||
}
|
||||
|
||||
const vpsRows = Array.isArray(data.vps) ? data.vps : []
|
||||
const vpsSql = `INSERT OR REPLACE INTO vps (id, ip, ipv6, additionalIps, dns, providerId, providerAccountId, country, city, datacenter, os, vcpu, ramGb, diskGb, diskType, virtualization, bandwidthTb, sshPort, rootUser, purpose, environment, project, projectId, monitoringEnabled, backupEnabled, status, tariffType, currency, dailyRate, monthlyRate, createdAt, paidUntil, notes, userOverrides)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`
|
||||
for (const v of vpsRows) {
|
||||
const additionalIps = Array.isArray(v.additionalIps) ? JSON.stringify(v.additionalIps) : '[]'
|
||||
const dailyRate = v.dailyRate === '' || v.dailyRate == null ? null : Number(v.dailyRate)
|
||||
const monthlyRate = v.monthlyRate === '' || v.monthlyRate == null ? null : Number(v.monthlyRate)
|
||||
const userOverrides = Array.isArray(v.userOverrides) ? JSON.stringify(v.userOverrides) : (v.userOverrides ?? '[]')
|
||||
run(
|
||||
vpsSql,
|
||||
v.id ?? '',
|
||||
v.ip ?? '',
|
||||
v.ipv6 ?? '',
|
||||
additionalIps,
|
||||
v.dns ?? '',
|
||||
v.providerId ?? '',
|
||||
v.providerAccountId ?? '',
|
||||
v.country ?? '',
|
||||
v.city ?? '',
|
||||
v.datacenter ?? '',
|
||||
v.os ?? '',
|
||||
v.vcpu ?? 0,
|
||||
v.ramGb ?? 0,
|
||||
v.diskGb ?? 0,
|
||||
v.diskType ?? '',
|
||||
v.virtualization ?? '',
|
||||
v.bandwidthTb ?? 0,
|
||||
v.sshPort ?? 22,
|
||||
v.rootUser ?? '',
|
||||
v.purpose ?? '',
|
||||
v.environment ?? '',
|
||||
v.project ?? '',
|
||||
v.projectId ?? null,
|
||||
v.monitoringEnabled ? 1 : 0,
|
||||
v.backupEnabled ? 1 : 0,
|
||||
v.status ?? 'active',
|
||||
v.tariffType ?? '',
|
||||
v.currency ?? '',
|
||||
dailyRate,
|
||||
monthlyRate,
|
||||
v.createdAt ?? '',
|
||||
v.paidUntil ?? '',
|
||||
v.notes ?? '',
|
||||
userOverrides,
|
||||
)
|
||||
}
|
||||
|
||||
const payments = Array.isArray(data.payments) ? data.payments : []
|
||||
for (const pm of payments) {
|
||||
run(
|
||||
`INSERT OR REPLACE INTO payments (id, type, date, amount, currency, providerAccountId, vpsId, note) VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,
|
||||
pm.id ?? '',
|
||||
pm.type ?? '',
|
||||
pm.date ?? '',
|
||||
Number(pm.amount) || 0,
|
||||
pm.currency ?? '',
|
||||
pm.providerAccountId ?? '',
|
||||
pm.vpsId ?? '',
|
||||
pm.note ?? '',
|
||||
)
|
||||
}
|
||||
|
||||
const ledger = Array.isArray(data.balanceLedger) ? data.balanceLedger : []
|
||||
for (const bl of ledger) {
|
||||
run(
|
||||
`INSERT OR REPLACE INTO balance_ledger (id, type, date, amount, currency, direction, providerAccountId, vpsId, note) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,
|
||||
bl.id ?? '',
|
||||
bl.type ?? '',
|
||||
bl.date ?? '',
|
||||
Number(bl.amount) || 0,
|
||||
bl.currency ?? '',
|
||||
bl.direction ?? '',
|
||||
bl.providerAccountId ?? '',
|
||||
bl.vpsId ?? '',
|
||||
bl.note ?? '',
|
||||
)
|
||||
}
|
||||
|
||||
const tariffs = Array.isArray(data.activeTariffs) ? data.activeTariffs : []
|
||||
for (const t of tariffs) {
|
||||
run(
|
||||
`INSERT OR REPLACE INTO active_tariffs (id, providerAccountId, providerId, externalId, datacenterKey, datacenterName, name, desc, vcpu, ramGb, diskGb, diskType, virtualization, channel, location, country, cpuModel, orderAvailable, price, syncedAt)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
|
||||
t.id ?? '',
|
||||
t.providerAccountId ?? '',
|
||||
t.providerId ?? '',
|
||||
t.externalId ?? '',
|
||||
t.datacenterKey ?? '',
|
||||
t.datacenterName ?? '',
|
||||
t.name ?? '',
|
||||
t.desc ?? '',
|
||||
t.vcpu ?? 0,
|
||||
t.ramGb ?? 0,
|
||||
t.diskGb ?? 0,
|
||||
t.diskType ?? '',
|
||||
t.virtualization ?? '',
|
||||
t.channel ?? '',
|
||||
t.location ?? '',
|
||||
t.country ?? '',
|
||||
t.cpuModel ?? '',
|
||||
t.orderAvailable ? 1 : 0,
|
||||
t.price ?? '',
|
||||
t.syncedAt ?? '',
|
||||
)
|
||||
}
|
||||
|
||||
const tso = Array.isArray(data.tariffSyncOptions) ? data.tariffSyncOptions : []
|
||||
for (const o of tso) {
|
||||
const dcs = typeof o.datacenters === 'string' ? o.datacenters : JSON.stringify(o.datacenters || [])
|
||||
const pers = typeof o.periods === 'string' ? o.periods : JSON.stringify(o.periods || [])
|
||||
run(
|
||||
`INSERT OR REPLACE INTO tariff_sync_options (providerAccountId, datacenters, periods, syncedAt) VALUES (?, ?, ?, ?)`,
|
||||
o.providerAccountId ?? '',
|
||||
dcs,
|
||||
pers,
|
||||
o.syncedAt ?? '',
|
||||
)
|
||||
}
|
||||
|
||||
const logs = Array.isArray(data.syncLog) ? data.syncLog : []
|
||||
for (const log of logs) {
|
||||
run(
|
||||
`INSERT OR REPLACE INTO sync_log (id, accountId, startedAt, finishedAt, status, vpsCount, paymentsCount, error, summary) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,
|
||||
log.id ?? '',
|
||||
log.accountId ?? '',
|
||||
log.startedAt ?? '',
|
||||
log.finishedAt ?? null,
|
||||
log.status ?? '',
|
||||
log.vpsCount ?? null,
|
||||
log.paymentsCount ?? null,
|
||||
log.error ?? null,
|
||||
typeof log.summary === 'string' ? log.summary : log.summary ? JSON.stringify(log.summary) : null,
|
||||
)
|
||||
}
|
||||
|
||||
saveDb()
|
||||
}
|
||||
|
||||
router.post('/database', express.raw({ limit: '100mb', type: '*/*' }), async (req, res) => {
|
||||
try {
|
||||
const buf = Buffer.isBuffer(req.body) ? req.body : Buffer.from(req.body || [])
|
||||
if (!buf.length) {
|
||||
return res.status(400).json({ error: 'Пустой файл' })
|
||||
}
|
||||
await reloadDatabaseFromBuffer(buf)
|
||||
const { startScheduler } = await import('../sync-scheduler.js')
|
||||
startScheduler()
|
||||
res.json({ ok: true })
|
||||
} catch (err) {
|
||||
console.error('Backup DB restore error:', err)
|
||||
res.status(500).json({ error: err.message || 'Восстановление не удалось' })
|
||||
}
|
||||
})
|
||||
|
||||
export default router
|
||||
@@ -0,0 +1,82 @@
|
||||
import { Router } from 'express'
|
||||
import { getDb } from '../db.js'
|
||||
|
||||
const router = Router()
|
||||
|
||||
router.get('/', (req, res) => {
|
||||
try {
|
||||
const db = getDb()
|
||||
const rows = db.prepare('SELECT * FROM balance_ledger ORDER BY date DESC').all()
|
||||
res.json(rows)
|
||||
} catch (err) {
|
||||
res.status(500).json({ error: err.message })
|
||||
}
|
||||
})
|
||||
|
||||
router.post('/', (req, res) => {
|
||||
try {
|
||||
const db = getDb()
|
||||
const r = req.body
|
||||
const id = r.id || `ledger-${Date.now()}-${Math.random().toString(36).slice(2, 9)}`
|
||||
db.prepare(`
|
||||
INSERT INTO balance_ledger (id, type, date, amount, currency, direction, providerAccountId, vpsId, note)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||
`).run(
|
||||
id,
|
||||
r.type ?? '',
|
||||
r.date ?? '',
|
||||
Number(r.amount) || 0,
|
||||
r.currency ?? '',
|
||||
r.direction ?? '',
|
||||
r.providerAccountId ?? '',
|
||||
r.vpsId ?? '',
|
||||
r.note ?? '',
|
||||
)
|
||||
const row = db.prepare('SELECT * FROM balance_ledger WHERE id = ?').get(id)
|
||||
res.status(201).json(row)
|
||||
} catch (err) {
|
||||
res.status(500).json({ error: err.message })
|
||||
}
|
||||
})
|
||||
|
||||
router.put('/:id', (req, res) => {
|
||||
try {
|
||||
const db = getDb()
|
||||
const { id } = req.params
|
||||
const r = req.body
|
||||
db.prepare(`
|
||||
UPDATE balance_ledger SET
|
||||
type = ?, date = ?, amount = ?, currency = ?, direction = ?, providerAccountId = ?, vpsId = ?, note = ?
|
||||
WHERE id = ?
|
||||
`).run(
|
||||
r.type ?? '',
|
||||
r.date ?? '',
|
||||
Number(r.amount) || 0,
|
||||
r.currency ?? '',
|
||||
r.direction ?? '',
|
||||
r.providerAccountId ?? '',
|
||||
r.vpsId ?? '',
|
||||
r.note ?? '',
|
||||
id,
|
||||
)
|
||||
const row = db.prepare('SELECT * FROM balance_ledger WHERE id = ?').get(id)
|
||||
if (!row) return res.status(404).json({ error: 'Not found' })
|
||||
res.json(row)
|
||||
} catch (err) {
|
||||
res.status(500).json({ error: err.message })
|
||||
}
|
||||
})
|
||||
|
||||
router.delete('/:id', (req, res) => {
|
||||
try {
|
||||
const db = getDb()
|
||||
const { id } = req.params
|
||||
const result = db.prepare('DELETE FROM balance_ledger WHERE id = ?').run(id)
|
||||
if (result.changes === 0) return res.status(404).json({ error: 'Not found' })
|
||||
res.status(204).send()
|
||||
} catch (err) {
|
||||
res.status(500).json({ error: err.message })
|
||||
}
|
||||
})
|
||||
|
||||
export default router
|
||||
@@ -0,0 +1,45 @@
|
||||
import { Router } from 'express'
|
||||
import { getDb } from '../db.js'
|
||||
import { rowToVps } from './vps.js'
|
||||
import { rowToSettings } from './settings.js'
|
||||
import { sanitizeAccount, rowToActiveTariff, rowToTariffSyncOptions } from '../utils/row-mappers.js'
|
||||
|
||||
const router = Router()
|
||||
|
||||
router.get('/', (req, res) => {
|
||||
try {
|
||||
const db = getDb()
|
||||
const vps = db.prepare('SELECT * FROM vps ORDER BY createdAt DESC').all()
|
||||
const providers = db.prepare('SELECT * FROM providers ORDER BY name').all()
|
||||
const providerAccounts = db.prepare('SELECT * FROM provider_accounts ORDER BY name').all()
|
||||
const payments = db.prepare('SELECT * FROM payments ORDER BY date DESC').all()
|
||||
const balanceLedger = db.prepare('SELECT * FROM balance_ledger ORDER BY date DESC').all()
|
||||
const settingsRows = db.prepare('SELECT * FROM settings ORDER BY id').all()
|
||||
const activeTariffs = db.prepare('SELECT * FROM active_tariffs ORDER BY name').all()
|
||||
const tariffSyncOptions = db.prepare('SELECT * FROM tariff_sync_options').all()
|
||||
let serverProjects = []
|
||||
try {
|
||||
serverProjects = db
|
||||
.prepare('SELECT id, name, color, sortOrder, notes, createdAt FROM server_projects ORDER BY name')
|
||||
.all()
|
||||
} catch {
|
||||
serverProjects = []
|
||||
}
|
||||
|
||||
res.json({
|
||||
vps: vps.map(rowToVps),
|
||||
serverProjects,
|
||||
providers,
|
||||
providerAccounts: providerAccounts.map(sanitizeAccount),
|
||||
payments,
|
||||
balanceLedger,
|
||||
settings: settingsRows.map(rowToSettings),
|
||||
activeTariffs: activeTariffs.map(rowToActiveTariff),
|
||||
tariffSyncOptions: tariffSyncOptions.map(rowToTariffSyncOptions),
|
||||
})
|
||||
} catch (err) {
|
||||
res.status(500).json({ error: err.message })
|
||||
}
|
||||
})
|
||||
|
||||
export default router
|
||||
@@ -0,0 +1,85 @@
|
||||
import { Router } from 'express'
|
||||
import { getDb, saveDb } from '../db.js'
|
||||
import { consolidateAllProviderApiSources } from '../db/migrations.js'
|
||||
|
||||
const router = Router()
|
||||
|
||||
router.post('/', (req, res) => {
|
||||
try {
|
||||
const db = getDb()
|
||||
const data = req.body
|
||||
if (!data || typeof data !== 'object') {
|
||||
return res.status(400).json({ error: 'Invalid payload' })
|
||||
}
|
||||
|
||||
const settingsList = Array.isArray(data.settings) ? data.settings : (data.settings ? [data.settings] : [])
|
||||
|
||||
if (Array.isArray(data.providers) && data.providers.length > 0) {
|
||||
const sql = `INSERT OR REPLACE INTO providers (id, name, website, contact, baseCurrency, usdRate, eurRate, notes, apiType, apiBaseUrl) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`
|
||||
for (const r of data.providers) {
|
||||
const p = typeof r === 'object' ? r : {}
|
||||
db.run(
|
||||
sql,
|
||||
p.id ?? '',
|
||||
p.name ?? '',
|
||||
p.website ?? '',
|
||||
p.contact ?? '',
|
||||
p.baseCurrency ?? '',
|
||||
p.usdRate ?? '',
|
||||
p.eurRate ?? '',
|
||||
p.notes ?? '',
|
||||
p.apiType ?? '',
|
||||
p.apiBaseUrl ?? '',
|
||||
)
|
||||
}
|
||||
}
|
||||
if (Array.isArray(data.providerAccounts) && data.providerAccounts.length > 0) {
|
||||
const sql = `INSERT OR REPLACE INTO provider_accounts (id, providerId, name, panelUrl, currency, billingMode, notes, apiType, apiBaseUrl, apiCredentials) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`
|
||||
for (const r of data.providerAccounts) {
|
||||
const acc = typeof r === 'object' ? r : {}
|
||||
db.run(sql, acc.id ?? '', acc.providerId ?? '', acc.name ?? '', acc.panelUrl ?? '', acc.currency ?? '', acc.billingMode ?? '', acc.notes ?? '', acc.apiType ?? '', acc.apiBaseUrl ?? '', acc.apiCredentials ?? '')
|
||||
}
|
||||
}
|
||||
if (Array.isArray(data.vps) && data.vps.length > 0) {
|
||||
const sql = `INSERT OR REPLACE INTO vps (id, ip, ipv6, additionalIps, dns, providerId, providerAccountId, country, city, datacenter, os, vcpu, ramGb, diskGb, diskType, virtualization, bandwidthTb, sshPort, rootUser, purpose, environment, project, projectId, monitoringEnabled, backupEnabled, status, tariffType, currency, dailyRate, monthlyRate, createdAt, paidUntil, notes, userOverrides) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`
|
||||
for (const r of data.vps) {
|
||||
const v = typeof r === 'object' ? r : {}
|
||||
const additionalIps = Array.isArray(v.additionalIps) ? JSON.stringify(v.additionalIps) : '[]'
|
||||
const dailyRate = v.dailyRate === '' || v.dailyRate == null ? null : Number(v.dailyRate)
|
||||
const monthlyRate = v.monthlyRate === '' || v.monthlyRate == null ? null : Number(v.monthlyRate)
|
||||
const userOverrides = Array.isArray(v.userOverrides) ? JSON.stringify(v.userOverrides) : (v.userOverrides ?? '[]')
|
||||
db.run(sql, v.id ?? '', v.ip ?? '', v.ipv6 ?? '', additionalIps, v.dns ?? '', v.providerId ?? '', v.providerAccountId ?? '', v.country ?? '', v.city ?? '', v.datacenter ?? '', v.os ?? '', v.vcpu ?? 0, v.ramGb ?? 0, v.diskGb ?? 0, v.diskType ?? '', v.virtualization ?? '', v.bandwidthTb ?? 0, v.sshPort ?? 22, v.rootUser ?? '', v.purpose ?? '', v.environment ?? '', v.project ?? '', v.projectId ?? null, v.monitoringEnabled ? 1 : 0, v.backupEnabled ? 1 : 0, v.status ?? 'active', v.tariffType ?? '', v.currency ?? '', dailyRate, monthlyRate, v.createdAt ?? '', v.paidUntil ?? '', v.notes ?? '', userOverrides)
|
||||
}
|
||||
}
|
||||
if (Array.isArray(data.payments) && data.payments.length > 0) {
|
||||
const sql = `INSERT OR REPLACE INTO payments (id, type, date, amount, currency, providerAccountId, vpsId, note) VALUES (?, ?, ?, ?, ?, ?, ?, ?)`
|
||||
for (const r of data.payments) {
|
||||
const pm = typeof r === 'object' ? r : {}
|
||||
db.run(sql, pm.id ?? '', pm.type ?? '', pm.date ?? '', Number(pm.amount) || 0, pm.currency ?? '', pm.providerAccountId ?? '', pm.vpsId ?? '', pm.note ?? '')
|
||||
}
|
||||
}
|
||||
if (Array.isArray(data.balanceLedger) && data.balanceLedger.length > 0) {
|
||||
const sql = `INSERT OR REPLACE INTO balance_ledger (id, type, date, amount, currency, direction, providerAccountId, vpsId, note) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`
|
||||
for (const r of data.balanceLedger) {
|
||||
const bl = typeof r === 'object' ? r : {}
|
||||
db.run(sql, bl.id ?? '', bl.type ?? '', bl.date ?? '', Number(bl.amount) || 0, bl.currency ?? '', bl.direction ?? '', bl.providerAccountId ?? '', bl.vpsId ?? '', bl.note ?? '')
|
||||
}
|
||||
}
|
||||
if (settingsList.length > 0) {
|
||||
const sql = `INSERT OR REPLACE INTO settings (id, baseCurrency, ratesUrl, autoConvert, ratesUpdatedAt, syncEnabled, syncIntervalMinutes) VALUES (?, ?, ?, ?, ?, ?, ?)`
|
||||
for (const r of settingsList) {
|
||||
const s = typeof r === 'object' ? r : {}
|
||||
db.run(sql, s.id ?? 'settings-main', s.baseCurrency ?? 'RUB', s.ratesUrl ?? '', s.autoConvert !== false ? 1 : 0, s.ratesUpdatedAt ?? '', s.syncEnabled ? 1 : 0, s.syncIntervalMinutes ?? 60)
|
||||
}
|
||||
}
|
||||
consolidateAllProviderApiSources(db)
|
||||
saveDb()
|
||||
|
||||
res.json({ ok: true })
|
||||
} catch (err) {
|
||||
console.error('Migrate error:', err)
|
||||
res.status(500).json({ error: err.message || 'Migration failed' })
|
||||
}
|
||||
})
|
||||
|
||||
export default router
|
||||
@@ -0,0 +1,80 @@
|
||||
import { Router } from 'express'
|
||||
import { getDb } from '../db.js'
|
||||
|
||||
const router = Router()
|
||||
|
||||
router.get('/', (req, res) => {
|
||||
try {
|
||||
const db = getDb()
|
||||
const rows = db.prepare('SELECT * FROM payments ORDER BY date DESC').all()
|
||||
res.json(rows)
|
||||
} catch (err) {
|
||||
res.status(500).json({ error: err.message })
|
||||
}
|
||||
})
|
||||
|
||||
router.post('/', (req, res) => {
|
||||
try {
|
||||
const db = getDb()
|
||||
const r = req.body
|
||||
const id = r.id || `pay-${Date.now()}-${Math.random().toString(36).slice(2, 9)}`
|
||||
db.prepare(`
|
||||
INSERT INTO payments (id, type, date, amount, currency, providerAccountId, vpsId, note)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
|
||||
`).run(
|
||||
id,
|
||||
r.type ?? '',
|
||||
r.date ?? '',
|
||||
Number(r.amount) || 0,
|
||||
r.currency ?? '',
|
||||
r.providerAccountId ?? '',
|
||||
r.vpsId ?? '',
|
||||
r.note ?? '',
|
||||
)
|
||||
const row = db.prepare('SELECT * FROM payments WHERE id = ?').get(id)
|
||||
res.status(201).json(row)
|
||||
} catch (err) {
|
||||
res.status(500).json({ error: err.message })
|
||||
}
|
||||
})
|
||||
|
||||
router.put('/:id', (req, res) => {
|
||||
try {
|
||||
const db = getDb()
|
||||
const { id } = req.params
|
||||
const r = req.body
|
||||
db.prepare(`
|
||||
UPDATE payments SET
|
||||
type = ?, date = ?, amount = ?, currency = ?, providerAccountId = ?, vpsId = ?, note = ?
|
||||
WHERE id = ?
|
||||
`).run(
|
||||
r.type ?? '',
|
||||
r.date ?? '',
|
||||
Number(r.amount) || 0,
|
||||
r.currency ?? '',
|
||||
r.providerAccountId ?? '',
|
||||
r.vpsId ?? '',
|
||||
r.note ?? '',
|
||||
id,
|
||||
)
|
||||
const row = db.prepare('SELECT * FROM payments WHERE id = ?').get(id)
|
||||
if (!row) return res.status(404).json({ error: 'Not found' })
|
||||
res.json(row)
|
||||
} catch (err) {
|
||||
res.status(500).json({ error: err.message })
|
||||
}
|
||||
})
|
||||
|
||||
router.delete('/:id', (req, res) => {
|
||||
try {
|
||||
const db = getDb()
|
||||
const { id } = req.params
|
||||
const result = db.prepare('DELETE FROM payments WHERE id = ?').run(id)
|
||||
if (result.changes === 0) return res.status(404).json({ error: 'Not found' })
|
||||
res.status(204).send()
|
||||
} catch (err) {
|
||||
res.status(500).json({ error: err.message })
|
||||
}
|
||||
})
|
||||
|
||||
export default router
|
||||
@@ -0,0 +1,60 @@
|
||||
import { Router } from 'express'
|
||||
import { getDb } from '../db.js'
|
||||
import {
|
||||
normalizeProjectNameInput,
|
||||
projectSuggestions,
|
||||
resolveOrCreateProject,
|
||||
} from '../projects-service.js'
|
||||
|
||||
const router = Router()
|
||||
|
||||
router.get('/', (req, res) => {
|
||||
try {
|
||||
const db = getDb()
|
||||
const rows = db
|
||||
.prepare('SELECT id, name, color, sortOrder, notes, createdAt FROM server_projects ORDER BY name')
|
||||
.all()
|
||||
res.json(rows)
|
||||
} catch (err) {
|
||||
res.status(500).json({ error: err.message })
|
||||
}
|
||||
})
|
||||
|
||||
router.get('/suggest', (req, res) => {
|
||||
try {
|
||||
const db = getDb()
|
||||
const q = req.query.q ?? ''
|
||||
const limit = req.query.limit != null ? Number(req.query.limit) : 20
|
||||
const rows = projectSuggestions(db, q, limit)
|
||||
res.json(rows)
|
||||
} catch (err) {
|
||||
res.status(500).json({ error: err.message })
|
||||
}
|
||||
})
|
||||
|
||||
router.post('/resolve-or-create', (req, res) => {
|
||||
try {
|
||||
const db = getDb()
|
||||
const name = req.body?.name
|
||||
const resolved = resolveOrCreateProject(db, name)
|
||||
res.json(resolved)
|
||||
} catch (err) {
|
||||
res.status(500).json({ error: err.message })
|
||||
}
|
||||
})
|
||||
|
||||
router.post('/', (req, res) => {
|
||||
try {
|
||||
const db = getDb()
|
||||
const name = normalizeProjectNameInput(req.body?.name)
|
||||
if (!name) {
|
||||
return res.status(400).json({ error: 'name is required' })
|
||||
}
|
||||
const resolved = resolveOrCreateProject(db, name)
|
||||
res.status(201).json(resolved)
|
||||
} catch (err) {
|
||||
res.status(500).json({ error: err.message })
|
||||
}
|
||||
})
|
||||
|
||||
export default router
|
||||
@@ -0,0 +1,105 @@
|
||||
import { Router } from 'express'
|
||||
import { getDb } from '../db.js'
|
||||
|
||||
const router = Router()
|
||||
|
||||
function sanitizeAccount(row) {
|
||||
if (!row) return row
|
||||
const { apiCredentials, ...rest } = row
|
||||
return { ...rest, apiCredentialsSet: Boolean(apiCredentials) }
|
||||
}
|
||||
|
||||
router.get('/', (req, res) => {
|
||||
try {
|
||||
const db = getDb()
|
||||
const rows = db.prepare('SELECT * FROM provider_accounts ORDER BY name').all()
|
||||
res.json(rows.map(sanitizeAccount))
|
||||
} catch (err) {
|
||||
res.status(500).json({ error: err.message })
|
||||
}
|
||||
})
|
||||
|
||||
router.post('/', (req, res) => {
|
||||
try {
|
||||
const db = getDb()
|
||||
const r = req.body
|
||||
const id = r.id || `account-${Date.now()}-${Math.random().toString(36).slice(2, 9)}`
|
||||
const alertBelow =
|
||||
r.balance_alert_below != null && r.balance_alert_below !== ''
|
||||
? Number(r.balance_alert_below)
|
||||
: null
|
||||
db.prepare(`
|
||||
INSERT INTO provider_accounts (id, providerId, name, panelUrl, currency, billingMode, notes, apiType, apiBaseUrl, apiCredentials, balance_alert_below)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, '', '', ?, ?)
|
||||
`).run(
|
||||
id,
|
||||
r.providerId ?? '',
|
||||
r.name ?? '',
|
||||
r.panelUrl ?? '',
|
||||
r.currency ?? '',
|
||||
r.billingMode ?? '',
|
||||
r.notes ?? '',
|
||||
r.apiCredentials ?? '',
|
||||
Number.isFinite(alertBelow) ? alertBelow : null,
|
||||
)
|
||||
const row = db.prepare('SELECT * FROM provider_accounts WHERE id = ?').get(id)
|
||||
res.status(201).json(sanitizeAccount(row))
|
||||
} catch (err) {
|
||||
res.status(500).json({ error: err.message })
|
||||
}
|
||||
})
|
||||
|
||||
router.put('/:id', (req, res) => {
|
||||
try {
|
||||
const db = getDb()
|
||||
const { id } = req.params
|
||||
const r = req.body
|
||||
const existing = db.prepare('SELECT * FROM provider_accounts WHERE id = ?').get(id)
|
||||
if (!existing) return res.status(404).json({ error: 'Not found' })
|
||||
const apiCredentials = r.apiCredentials !== undefined ? String(r.apiCredentials || '') : (existing.apiCredentials || '')
|
||||
let balanceAlertBelow = existing.balance_alert_below
|
||||
if (r.balance_alert_below !== undefined) {
|
||||
const v = r.balance_alert_below
|
||||
balanceAlertBelow =
|
||||
v === '' || v == null
|
||||
? null
|
||||
: Number.isFinite(Number(v))
|
||||
? Number(v)
|
||||
: null
|
||||
}
|
||||
db.prepare(`
|
||||
UPDATE provider_accounts SET
|
||||
providerId = ?, name = ?, panelUrl = ?, currency = ?, billingMode = ?, notes = ?,
|
||||
apiType = '', apiBaseUrl = '', apiCredentials = ?, balance_alert_below = ?
|
||||
WHERE id = ?
|
||||
`).run(
|
||||
r.providerId ?? existing.providerId ?? '',
|
||||
r.name ?? existing.name ?? '',
|
||||
r.panelUrl ?? existing.panelUrl ?? '',
|
||||
r.currency ?? existing.currency ?? '',
|
||||
r.billingMode ?? existing.billingMode ?? '',
|
||||
r.notes ?? existing.notes ?? '',
|
||||
apiCredentials,
|
||||
balanceAlertBelow,
|
||||
id,
|
||||
)
|
||||
const row = db.prepare('SELECT * FROM provider_accounts WHERE id = ?').get(id)
|
||||
res.json(sanitizeAccount(row))
|
||||
} catch (err) {
|
||||
res.status(500).json({ error: err.message })
|
||||
}
|
||||
})
|
||||
|
||||
router.delete('/:id', (req, res) => {
|
||||
try {
|
||||
const db = getDb()
|
||||
const { id } = req.params
|
||||
const result = db.prepare('DELETE FROM provider_accounts WHERE id = ?').run(id)
|
||||
if (result.changes === 0) return res.status(404).json({ error: 'Not found' })
|
||||
res.status(204).send()
|
||||
} catch (err) {
|
||||
res.status(500).json({ error: err.message })
|
||||
}
|
||||
})
|
||||
|
||||
export default router
|
||||
@@ -0,0 +1,89 @@
|
||||
import { Router } from 'express'
|
||||
import { getDb } from '../db.js'
|
||||
|
||||
const router = Router()
|
||||
|
||||
router.get('/', (req, res) => {
|
||||
try {
|
||||
const db = getDb()
|
||||
const rows = db.prepare('SELECT * FROM providers ORDER BY name').all()
|
||||
res.json(rows)
|
||||
} catch (err) {
|
||||
res.status(500).json({ error: err.message })
|
||||
}
|
||||
})
|
||||
|
||||
router.post('/', (req, res) => {
|
||||
try {
|
||||
const db = getDb()
|
||||
const r = req.body
|
||||
const id = r.id || `provider-${Date.now()}-${Math.random().toString(36).slice(2, 9)}`
|
||||
db.prepare(`
|
||||
INSERT INTO providers (id, name, website, contact, baseCurrency, usdRate, eurRate, notes, apiType, apiBaseUrl)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||
`).run(
|
||||
id,
|
||||
r.name ?? '',
|
||||
r.website ?? '',
|
||||
r.contact ?? '',
|
||||
r.baseCurrency ?? '',
|
||||
r.usdRate ?? '',
|
||||
r.eurRate ?? '',
|
||||
r.notes ?? '',
|
||||
r.apiType ?? '',
|
||||
r.apiBaseUrl ?? '',
|
||||
)
|
||||
const row = db.prepare('SELECT * FROM providers WHERE id = ?').get(id)
|
||||
res.status(201).json(row)
|
||||
} catch (err) {
|
||||
res.status(500).json({ error: err.message })
|
||||
}
|
||||
})
|
||||
|
||||
router.put('/:id', (req, res) => {
|
||||
try {
|
||||
const db = getDb()
|
||||
const { id } = req.params
|
||||
const r = req.body
|
||||
const existing = db.prepare('SELECT * FROM providers WHERE id = ?').get(id)
|
||||
if (!existing) return res.status(404).json({ error: 'Not found' })
|
||||
const apiType = r.apiType !== undefined ? String(r.apiType || '') : (existing.apiType || '')
|
||||
const apiBaseUrl =
|
||||
r.apiBaseUrl !== undefined ? String(r.apiBaseUrl || '') : (existing.apiBaseUrl || '')
|
||||
db.prepare(`
|
||||
UPDATE providers SET
|
||||
name = ?, website = ?, contact = ?, baseCurrency = ?, usdRate = ?, eurRate = ?, notes = ?,
|
||||
apiType = ?, apiBaseUrl = ?
|
||||
WHERE id = ?
|
||||
`).run(
|
||||
r.name ?? '',
|
||||
r.website ?? '',
|
||||
r.contact ?? '',
|
||||
r.baseCurrency ?? '',
|
||||
r.usdRate ?? '',
|
||||
r.eurRate ?? '',
|
||||
r.notes ?? '',
|
||||
apiType,
|
||||
apiBaseUrl,
|
||||
id,
|
||||
)
|
||||
const row = db.prepare('SELECT * FROM providers WHERE id = ?').get(id)
|
||||
res.json(row)
|
||||
} catch (err) {
|
||||
res.status(500).json({ error: err.message })
|
||||
}
|
||||
})
|
||||
|
||||
router.delete('/:id', (req, res) => {
|
||||
try {
|
||||
const db = getDb()
|
||||
const { id } = req.params
|
||||
const result = db.prepare('DELETE FROM providers WHERE id = ?').run(id)
|
||||
if (result.changes === 0) return res.status(404).json({ error: 'Not found' })
|
||||
res.status(204).send()
|
||||
} catch (err) {
|
||||
res.status(500).json({ error: err.message })
|
||||
}
|
||||
})
|
||||
|
||||
export default router
|
||||
@@ -0,0 +1,22 @@
|
||||
import { Router } from 'express'
|
||||
|
||||
const router = Router()
|
||||
|
||||
router.get('/', async (req, res) => {
|
||||
const url = req.query.url
|
||||
if (!url) {
|
||||
return res.status(400).json({ error: 'Missing url parameter' })
|
||||
}
|
||||
try {
|
||||
const response = await fetch(url, { signal: AbortSignal.timeout(10_000) })
|
||||
if (!response.ok) {
|
||||
return res.status(502).json({ error: `Upstream returned ${response.status}` })
|
||||
}
|
||||
const data = await response.json()
|
||||
res.json(data)
|
||||
} catch (err) {
|
||||
res.status(502).json({ error: err.message || 'Failed to fetch rates' })
|
||||
}
|
||||
})
|
||||
|
||||
export default router
|
||||
@@ -0,0 +1,182 @@
|
||||
import { Router } from 'express'
|
||||
import { getDb } from '../db.js'
|
||||
import { startScheduler } from '../sync-scheduler.js'
|
||||
import { sendTelegramMessage } from '../telegram.js'
|
||||
|
||||
const router = Router()
|
||||
|
||||
export function rowToSettings(row) {
|
||||
if (!row) return null
|
||||
let customFields = []
|
||||
if (row.customFields) {
|
||||
try {
|
||||
customFields = JSON.parse(row.customFields)
|
||||
} catch {
|
||||
customFields = []
|
||||
}
|
||||
}
|
||||
const { telegramBotToken, ...rest } = row
|
||||
return {
|
||||
...rest,
|
||||
telegramBotTokenSet: Boolean(telegramBotToken?.trim()),
|
||||
autoConvert: Boolean(row.autoConvert),
|
||||
syncEnabled: Boolean(row.syncEnabled),
|
||||
notifyPaymentExpiryEnabled: Boolean(row.notifyPaymentExpiryEnabled),
|
||||
notifyNewTariffsEnabled: Boolean(row.notifyNewTariffsEnabled),
|
||||
notifyLowBalanceEnabled: Boolean(row.notifyLowBalanceEnabled),
|
||||
notifySyncDigestEnabled: Boolean(row.notifySyncDigestEnabled),
|
||||
customFields: Array.isArray(customFields) ? customFields : [],
|
||||
}
|
||||
}
|
||||
|
||||
router.post('/telegram/test', async (req, res) => {
|
||||
try {
|
||||
const db = getDb()
|
||||
const row = db.prepare('SELECT telegramBotToken, telegramChatId, telegramMessageThreadId FROM settings WHERE id = ?').get('settings-main')
|
||||
if (!row?.telegramBotToken?.trim() || !row?.telegramChatId?.trim()) {
|
||||
return res.status(400).json({ ok: false, error: 'Укажите токен бота и Chat ID в настройках' })
|
||||
}
|
||||
const text = '✅ <b>Тестовое уведомление</b>\n\nVPS Tracker — уведомления настроены корректно.'
|
||||
await sendTelegramMessage(row.telegramBotToken, row.telegramChatId, text, row.telegramMessageThreadId || undefined)
|
||||
res.json({ ok: true })
|
||||
} catch (err) {
|
||||
res.status(500).json({ ok: false, error: err.message || 'Ошибка отправки' })
|
||||
}
|
||||
})
|
||||
|
||||
router.get('/', (req, res) => {
|
||||
try {
|
||||
const db = getDb()
|
||||
const rows = db.prepare('SELECT * FROM settings ORDER BY id').all()
|
||||
res.json(rows.map(rowToSettings))
|
||||
} catch (err) {
|
||||
res.status(500).json({ error: err.message })
|
||||
}
|
||||
})
|
||||
|
||||
function serializeCustomFields(val) {
|
||||
if (val == null) return null
|
||||
if (Array.isArray(val)) return JSON.stringify(val)
|
||||
if (typeof val === 'string') return val || null
|
||||
return null
|
||||
}
|
||||
|
||||
router.put('/:id', (req, res) => {
|
||||
try {
|
||||
const db = getDb()
|
||||
const { id } = req.params
|
||||
const r = req.body
|
||||
const existing = db.prepare('SELECT * FROM settings WHERE id = ?').get(id)
|
||||
const syncEnabled = r.syncEnabled !== undefined ? (r.syncEnabled ? 1 : 0) : (existing?.syncEnabled ? 1 : 0)
|
||||
const syncIntervalMinutes = r.syncIntervalMinutes !== undefined ? Math.max(15, Number(r.syncIntervalMinutes) || 60) : (existing?.syncIntervalMinutes ?? 60)
|
||||
const syncTariffsIntervalMinutes = r.syncTariffsIntervalMinutes !== undefined ? Math.max(60, Number(r.syncTariffsIntervalMinutes) || 1440) : (existing?.syncTariffsIntervalMinutes ?? 1440)
|
||||
const notifyPaymentExpiryEnabled = r.notifyPaymentExpiryEnabled !== undefined ? (r.notifyPaymentExpiryEnabled ? 1 : 0) : (existing?.notifyPaymentExpiryEnabled ? 1 : 0)
|
||||
const notifyNewTariffsEnabled = r.notifyNewTariffsEnabled !== undefined ? (r.notifyNewTariffsEnabled ? 1 : 0) : (existing?.notifyNewTariffsEnabled ? 1 : 0)
|
||||
const notifyLowBalanceEnabled = r.notifyLowBalanceEnabled !== undefined ? (r.notifyLowBalanceEnabled ? 1 : 0) : (existing?.notifyLowBalanceEnabled ? 1 : 0)
|
||||
const notifySyncDigestEnabled = r.notifySyncDigestEnabled !== undefined ? (r.notifySyncDigestEnabled ? 1 : 0) : (existing?.notifySyncDigestEnabled ? 1 : 0)
|
||||
const telegramBotToken = r.telegramBotToken !== undefined ? (r.telegramBotToken || '') : (existing?.telegramBotToken ?? '')
|
||||
const telegramChatId = r.telegramChatId !== undefined ? (r.telegramChatId || '') : (existing?.telegramChatId ?? '')
|
||||
const telegramMessageThreadId = r.telegramMessageThreadId !== undefined ? (r.telegramMessageThreadId || '') : (existing?.telegramMessageThreadId ?? '')
|
||||
const customFields = serializeCustomFields(r.customFields ?? existing?.customFields)
|
||||
if (existing) {
|
||||
db.prepare(`
|
||||
UPDATE settings SET
|
||||
baseCurrency = ?, ratesUrl = ?, autoConvert = ?, ratesUpdatedAt = ?, syncEnabled = ?, syncIntervalMinutes = ?, syncTariffsIntervalMinutes = ?,
|
||||
telegramBotToken = ?, telegramChatId = ?, telegramMessageThreadId = ?, notifyPaymentExpiryEnabled = ?, notifyNewTariffsEnabled = ?, customFields = ?,
|
||||
notifyLowBalanceEnabled = ?, notifySyncDigestEnabled = ?
|
||||
WHERE id = ?
|
||||
`).run(
|
||||
r.baseCurrency ?? existing.baseCurrency ?? 'RUB',
|
||||
r.ratesUrl ?? existing.ratesUrl ?? '',
|
||||
r.autoConvert !== undefined ? (r.autoConvert !== false ? 1 : 0) : (existing.autoConvert ? 1 : 0),
|
||||
r.ratesUpdatedAt ?? existing.ratesUpdatedAt ?? '',
|
||||
syncEnabled,
|
||||
syncIntervalMinutes,
|
||||
syncTariffsIntervalMinutes,
|
||||
telegramBotToken,
|
||||
telegramChatId,
|
||||
telegramMessageThreadId,
|
||||
notifyPaymentExpiryEnabled,
|
||||
notifyNewTariffsEnabled,
|
||||
customFields,
|
||||
notifyLowBalanceEnabled,
|
||||
notifySyncDigestEnabled,
|
||||
id,
|
||||
)
|
||||
} else {
|
||||
db.prepare(`
|
||||
INSERT INTO settings (id, baseCurrency, ratesUrl, autoConvert, ratesUpdatedAt, syncEnabled, syncIntervalMinutes, syncTariffsIntervalMinutes, telegramBotToken, telegramChatId, telegramMessageThreadId, notifyPaymentExpiryEnabled, notifyNewTariffsEnabled, customFields, notifyLowBalanceEnabled, notifySyncDigestEnabled)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||
`).run(
|
||||
id,
|
||||
r.baseCurrency ?? 'RUB',
|
||||
r.ratesUrl ?? '',
|
||||
r.autoConvert !== false ? 1 : 0,
|
||||
r.ratesUpdatedAt ?? '',
|
||||
syncEnabled,
|
||||
syncIntervalMinutes,
|
||||
syncTariffsIntervalMinutes,
|
||||
telegramBotToken,
|
||||
telegramChatId,
|
||||
telegramMessageThreadId,
|
||||
notifyPaymentExpiryEnabled,
|
||||
notifyNewTariffsEnabled,
|
||||
customFields,
|
||||
notifyLowBalanceEnabled,
|
||||
notifySyncDigestEnabled,
|
||||
)
|
||||
}
|
||||
startScheduler()
|
||||
const row = db.prepare('SELECT * FROM settings WHERE id = ?').get(id)
|
||||
res.json(rowToSettings(row))
|
||||
} catch (err) {
|
||||
res.status(500).json({ error: err.message })
|
||||
}
|
||||
})
|
||||
|
||||
router.post('/', (req, res) => {
|
||||
try {
|
||||
const db = getDb()
|
||||
const r = req.body
|
||||
const id = r.id ?? 'settings-main'
|
||||
const syncEnabled = r.syncEnabled ? 1 : 0
|
||||
const syncIntervalMinutes = Math.max(15, Number(r.syncIntervalMinutes) || 60)
|
||||
const syncTariffsIntervalMinutes = Math.max(60, Number(r.syncTariffsIntervalMinutes) || 1440)
|
||||
const notifyPaymentExpiryEnabled = r.notifyPaymentExpiryEnabled ? 1 : 0
|
||||
const notifyNewTariffsEnabled = r.notifyNewTariffsEnabled ? 1 : 0
|
||||
const notifyLowBalanceEnabled = r.notifyLowBalanceEnabled ? 1 : 0
|
||||
const notifySyncDigestEnabled = r.notifySyncDigestEnabled ? 1 : 0
|
||||
const telegramBotToken = r.telegramBotToken ?? ''
|
||||
const telegramChatId = r.telegramChatId ?? ''
|
||||
const telegramMessageThreadId = r.telegramMessageThreadId ?? ''
|
||||
const customFields = serializeCustomFields(r.customFields)
|
||||
db.prepare(`
|
||||
INSERT INTO settings (id, baseCurrency, ratesUrl, autoConvert, ratesUpdatedAt, syncEnabled, syncIntervalMinutes, syncTariffsIntervalMinutes, telegramBotToken, telegramChatId, telegramMessageThreadId, notifyPaymentExpiryEnabled, notifyNewTariffsEnabled, customFields, notifyLowBalanceEnabled, notifySyncDigestEnabled)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||
`).run(
|
||||
id,
|
||||
r.baseCurrency ?? 'RUB',
|
||||
r.ratesUrl ?? 'https://www.cbr-xml-daily.ru/latest.js',
|
||||
r.autoConvert !== false ? 1 : 0,
|
||||
r.ratesUpdatedAt ?? '',
|
||||
syncEnabled,
|
||||
syncIntervalMinutes,
|
||||
syncTariffsIntervalMinutes,
|
||||
telegramBotToken,
|
||||
telegramChatId,
|
||||
telegramMessageThreadId,
|
||||
notifyPaymentExpiryEnabled,
|
||||
notifyNewTariffsEnabled,
|
||||
customFields,
|
||||
notifyLowBalanceEnabled,
|
||||
notifySyncDigestEnabled,
|
||||
)
|
||||
startScheduler()
|
||||
const row = db.prepare('SELECT * FROM settings WHERE id = ?').get(id)
|
||||
res.status(201).json(rowToSettings(row))
|
||||
} catch (err) {
|
||||
res.status(500).json({ error: err.message })
|
||||
}
|
||||
})
|
||||
|
||||
export default router
|
||||
@@ -0,0 +1,120 @@
|
||||
import { Router } from 'express'
|
||||
import { getDb } from '../db.js'
|
||||
import { fetchDashboardInfo, testConnection } from '../adapters/billmanager/index.js'
|
||||
import { runBillmanagerAccountSync } from '../sync-account-job.js'
|
||||
import { billmanagerAccountRowForSync } from '../utils/billmanager-context.js'
|
||||
|
||||
const router = Router()
|
||||
|
||||
router.post('/test-connection', async (req, res) => {
|
||||
try {
|
||||
const { apiBaseUrl, apiCredentials } = req.body || {}
|
||||
if (!apiBaseUrl?.trim() || !apiCredentials?.trim()) {
|
||||
return res.status(400).json({ ok: false, error: 'Укажите URL и учётные данные' })
|
||||
}
|
||||
const result = await testConnection(apiBaseUrl.trim(), apiCredentials.trim())
|
||||
res.json(result)
|
||||
} catch (err) {
|
||||
res.status(500).json({ ok: false, error: err.message || 'Ошибка проверки' })
|
||||
}
|
||||
})
|
||||
|
||||
router.get('/status', (req, res) => {
|
||||
try {
|
||||
const db = getDb()
|
||||
const rows = db.prepare(`
|
||||
SELECT id, accountId, startedAt, finishedAt, status, vpsCount, paymentsCount, error, summary
|
||||
FROM sync_log ORDER BY startedAt DESC LIMIT 50
|
||||
`).all()
|
||||
res.json(
|
||||
rows.map((row) => {
|
||||
let summaryParsed = null
|
||||
if (row.summary) {
|
||||
try {
|
||||
summaryParsed = JSON.parse(row.summary)
|
||||
} catch {
|
||||
summaryParsed = null
|
||||
}
|
||||
}
|
||||
return { ...row, summary: summaryParsed }
|
||||
}),
|
||||
)
|
||||
} catch (err) {
|
||||
res.status(500).json({ error: err.message })
|
||||
}
|
||||
})
|
||||
|
||||
router.get('/:accountId/balance', async (req, res) => {
|
||||
try {
|
||||
const db = getDb()
|
||||
const { accountId } = req.params
|
||||
const row = db.prepare('SELECT * FROM provider_accounts WHERE id = ?').get(accountId)
|
||||
if (!row) {
|
||||
return res.status(404).json({ error: 'Account not found' })
|
||||
}
|
||||
const provider = row.providerId
|
||||
? db.prepare('SELECT * FROM providers WHERE id = ?').get(row.providerId)
|
||||
: null
|
||||
const syncRow = billmanagerAccountRowForSync(row, provider)
|
||||
if (!syncRow) {
|
||||
return res.status(400).json({
|
||||
error:
|
||||
'Укажите в настройках хостера тип API BILLmanager и URL; в аккаунте — логин и пароль API',
|
||||
})
|
||||
}
|
||||
const info = await fetchDashboardInfo(syncRow.apiBaseUrl, syncRow.apiCredentials.trim(), {
|
||||
fallbackCurrency: row.currency,
|
||||
})
|
||||
db.run(
|
||||
'UPDATE provider_accounts SET balance_api=?, balance_currency=?, balance_updated_at=?, enoughmoneyto=? WHERE id=?',
|
||||
info.balance,
|
||||
info.currency || 'RUB',
|
||||
new Date().toISOString(),
|
||||
info.enoughmoneyto || '',
|
||||
accountId,
|
||||
)
|
||||
res.json({ ok: true, balance: info })
|
||||
} catch (err) {
|
||||
console.error('Balance fetch error:', err)
|
||||
res.status(500).json({ ok: false, error: err.message || 'Failed to fetch balance' })
|
||||
}
|
||||
})
|
||||
|
||||
router.post('/:accountId', async (req, res) => {
|
||||
try {
|
||||
const db = getDb()
|
||||
const { accountId } = req.params
|
||||
const { onlyTariffs = false } = req.body || {}
|
||||
const row = db.prepare('SELECT * FROM provider_accounts WHERE id = ?').get(accountId)
|
||||
if (!row) {
|
||||
return res.status(404).json({ error: 'Account not found' })
|
||||
}
|
||||
const provider = row.providerId
|
||||
? db.prepare('SELECT * FROM providers WHERE id = ?').get(row.providerId)
|
||||
: null
|
||||
const syncRow = billmanagerAccountRowForSync(row, provider)
|
||||
if (!syncRow) {
|
||||
return res.status(400).json({
|
||||
error:
|
||||
'Укажите в настройках хостера тип API BILLmanager и URL; в аккаунте — логин и пароль API',
|
||||
})
|
||||
}
|
||||
|
||||
const opts = onlyTariffs ? { skipVpsPayments: true } : { skipTariffs: true }
|
||||
const result = await runBillmanagerAccountSync(syncRow, opts)
|
||||
|
||||
res.json({
|
||||
ok: true,
|
||||
synced: {
|
||||
vpsCount: result.vpsCount,
|
||||
paymentsCount: result.paymentsCount,
|
||||
tariffsCount: result.tariffsCount ?? 0,
|
||||
},
|
||||
})
|
||||
} catch (err) {
|
||||
console.error('Sync error:', err)
|
||||
res.status(500).json({ ok: false, error: err.message || 'Sync failed' })
|
||||
}
|
||||
})
|
||||
|
||||
export default router
|
||||
@@ -0,0 +1,304 @@
|
||||
import { Router } from 'express'
|
||||
import { getDb } from '../db.js'
|
||||
import { resolveOrCreateProject } from '../projects-service.js'
|
||||
|
||||
const router = Router()
|
||||
|
||||
function projectColumnsForSave(db, projectInput) {
|
||||
const resolved = resolveOrCreateProject(db, projectInput)
|
||||
if (!resolved.id) {
|
||||
return { project: '', projectId: '' }
|
||||
}
|
||||
return { project: resolved.name, projectId: resolved.id }
|
||||
}
|
||||
|
||||
export function rowToVps(row) {
|
||||
if (!row) return null
|
||||
let additionalIps = []
|
||||
try {
|
||||
additionalIps = row.additionalIps ? JSON.parse(row.additionalIps) : []
|
||||
} catch {
|
||||
additionalIps = []
|
||||
}
|
||||
let userOverrides = []
|
||||
try {
|
||||
userOverrides = row.userOverrides ? JSON.parse(row.userOverrides) : []
|
||||
} catch {
|
||||
userOverrides = []
|
||||
}
|
||||
return {
|
||||
...row,
|
||||
additionalIps,
|
||||
userOverrides,
|
||||
projectId: row.projectId ?? '',
|
||||
monitoringEnabled: Boolean(row.monitoringEnabled),
|
||||
backupEnabled: Boolean(row.backupEnabled),
|
||||
dailyRate: row.dailyRate != null ? row.dailyRate : '',
|
||||
monthlyRate: row.monthlyRate != null ? row.monthlyRate : '',
|
||||
}
|
||||
}
|
||||
|
||||
router.get('/', (req, res) => {
|
||||
try {
|
||||
const db = getDb()
|
||||
const rows = db.prepare('SELECT * FROM vps ORDER BY createdAt DESC').all()
|
||||
res.json(rows.map(rowToVps))
|
||||
} catch (err) {
|
||||
res.status(500).json({ error: err.message })
|
||||
}
|
||||
})
|
||||
|
||||
router.post('/', (req, res) => {
|
||||
try {
|
||||
const db = getDb()
|
||||
const r = req.body
|
||||
const id = r.id || `vps-${Date.now()}-${Math.random().toString(36).slice(2, 9)}`
|
||||
const additionalIps = Array.isArray(r.additionalIps) ? JSON.stringify(r.additionalIps) : '[]'
|
||||
const dailyRate = r.dailyRate === '' || r.dailyRate == null ? null : Number(r.dailyRate)
|
||||
const monthlyRate = r.monthlyRate === '' || r.monthlyRate == null ? null : Number(r.monthlyRate)
|
||||
const { project, projectId } = projectColumnsForSave(db, r.project)
|
||||
|
||||
db.prepare(`
|
||||
INSERT INTO vps (
|
||||
id, ip, ipv6, additionalIps, dns, providerId, providerAccountId, country, city, datacenter,
|
||||
os, vcpu, ramGb, diskGb, diskType, virtualization, bandwidthTb, sshPort, rootUser,
|
||||
purpose, environment, project, projectId, monitoringEnabled, backupEnabled, status, tariffType,
|
||||
currency, dailyRate, monthlyRate, createdAt, paidUntil, notes, userOverrides
|
||||
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||
`).run(
|
||||
id,
|
||||
r.ip ?? '',
|
||||
r.ipv6 ?? '',
|
||||
additionalIps,
|
||||
r.dns ?? '',
|
||||
r.providerId ?? '',
|
||||
r.providerAccountId ?? '',
|
||||
r.country ?? '',
|
||||
r.city ?? '',
|
||||
r.datacenter ?? '',
|
||||
r.os ?? '',
|
||||
r.vcpu ?? 0,
|
||||
r.ramGb ?? 0,
|
||||
r.diskGb ?? 0,
|
||||
r.diskType ?? '',
|
||||
r.virtualization ?? '',
|
||||
r.bandwidthTb ?? 0,
|
||||
r.sshPort ?? 22,
|
||||
r.rootUser ?? '',
|
||||
r.purpose ?? '',
|
||||
r.environment ?? '',
|
||||
project,
|
||||
projectId || null,
|
||||
r.monitoringEnabled ? 1 : 0,
|
||||
r.backupEnabled ? 1 : 0,
|
||||
r.status ?? 'active',
|
||||
r.tariffType ?? '',
|
||||
r.currency ?? '',
|
||||
dailyRate,
|
||||
monthlyRate,
|
||||
r.createdAt ?? new Date().toISOString().slice(0, 10),
|
||||
r.paidUntil ?? '',
|
||||
r.notes ?? '',
|
||||
r.userOverrides ? (Array.isArray(r.userOverrides) ? JSON.stringify(r.userOverrides) : r.userOverrides) : '[]',
|
||||
)
|
||||
const row = db.prepare('SELECT * FROM vps WHERE id = ?').get(id)
|
||||
res.status(201).json(rowToVps(row))
|
||||
} catch (err) {
|
||||
res.status(500).json({ error: err.message })
|
||||
}
|
||||
})
|
||||
|
||||
const USER_OVERRIDABLE_FIELDS = ['country', 'city', 'datacenter', 'os', 'vcpu', 'ramGb', 'diskGb', 'diskType', 'virtualization', 'purpose', 'environment', 'project', 'notes', 'sshPort', 'rootUser', 'bandwidthTb', 'monitoringEnabled', 'backupEnabled']
|
||||
|
||||
router.put('/:id', (req, res) => {
|
||||
try {
|
||||
const db = getDb()
|
||||
const { id } = req.params
|
||||
const r = req.body
|
||||
const existing = db.prepare('SELECT * FROM vps WHERE id = ?').get(id)
|
||||
if (!existing) return res.status(404).json({ error: 'Not found' })
|
||||
|
||||
let userOverrides = []
|
||||
try {
|
||||
userOverrides = existing.userOverrides ? JSON.parse(existing.userOverrides) : []
|
||||
} catch {
|
||||
userOverrides = []
|
||||
}
|
||||
const clearOverrides =
|
||||
r.userOverrides === 'clear' || (Array.isArray(r.userOverrides) && r.userOverrides.length === 0)
|
||||
if (clearOverrides) {
|
||||
userOverrides = []
|
||||
}
|
||||
|
||||
const additionalIps = Array.isArray(r.additionalIps) ? JSON.stringify(r.additionalIps) : '[]'
|
||||
const dailyRate = r.dailyRate === '' || r.dailyRate == null ? null : Number(r.dailyRate)
|
||||
const monthlyRate = r.monthlyRate === '' || r.monthlyRate == null ? null : Number(r.monthlyRate)
|
||||
|
||||
let projectOut = existing.project ?? ''
|
||||
let projectIdOut = existing.projectId ?? ''
|
||||
if (r.project !== undefined) {
|
||||
const resolved = projectColumnsForSave(db, r.project)
|
||||
projectOut = resolved.project
|
||||
projectIdOut = resolved.projectId
|
||||
} else if (r.projectId !== undefined) {
|
||||
if (!r.projectId) {
|
||||
projectOut = ''
|
||||
projectIdOut = ''
|
||||
} else {
|
||||
const prow = db.prepare('SELECT name FROM server_projects WHERE id = ?').get(r.projectId)
|
||||
projectOut = prow?.name ?? ''
|
||||
projectIdOut = r.projectId
|
||||
}
|
||||
}
|
||||
|
||||
if (!clearOverrides) {
|
||||
for (const f of USER_OVERRIDABLE_FIELDS) {
|
||||
if (f === 'project') {
|
||||
const projectChanged =
|
||||
String(projectOut ?? '') !== String(existing.project ?? '') ||
|
||||
String(projectIdOut ?? '') !== String(existing.projectId ?? '')
|
||||
if (projectChanged && !userOverrides.includes('project')) {
|
||||
userOverrides.push('project')
|
||||
}
|
||||
continue
|
||||
}
|
||||
const newVal = r[f]
|
||||
const oldVal = existing[f]
|
||||
const changed = String(newVal ?? '') !== String(oldVal ?? '')
|
||||
if (changed && !userOverrides.includes(f)) {
|
||||
userOverrides.push(f)
|
||||
}
|
||||
}
|
||||
}
|
||||
const userOverridesJson = JSON.stringify([...new Set(userOverrides)])
|
||||
|
||||
db.prepare(`
|
||||
UPDATE vps SET
|
||||
ip = ?, ipv6 = ?, additionalIps = ?, dns = ?, providerId = ?, providerAccountId = ?,
|
||||
country = ?, city = ?, datacenter = ?, os = ?, vcpu = ?, ramGb = ?, diskGb = ?, diskType = ?,
|
||||
virtualization = ?, bandwidthTb = ?, sshPort = ?, rootUser = ?, purpose = ?, environment = ?,
|
||||
project = ?, projectId = ?, monitoringEnabled = ?, backupEnabled = ?, status = ?, tariffType = ?,
|
||||
currency = ?, dailyRate = ?, monthlyRate = ?, createdAt = ?, paidUntil = ?, notes = ?,
|
||||
userOverrides = ?
|
||||
WHERE id = ?
|
||||
`).run(
|
||||
r.ip ?? '',
|
||||
r.ipv6 ?? '',
|
||||
additionalIps,
|
||||
r.dns ?? '',
|
||||
r.providerId ?? '',
|
||||
r.providerAccountId ?? '',
|
||||
r.country ?? '',
|
||||
r.city ?? '',
|
||||
r.datacenter ?? '',
|
||||
r.os ?? '',
|
||||
r.vcpu ?? 0,
|
||||
r.ramGb ?? 0,
|
||||
r.diskGb ?? 0,
|
||||
r.diskType ?? '',
|
||||
r.virtualization ?? '',
|
||||
r.bandwidthTb ?? 0,
|
||||
r.sshPort ?? 22,
|
||||
r.rootUser ?? '',
|
||||
r.purpose ?? '',
|
||||
r.environment ?? '',
|
||||
projectOut,
|
||||
projectIdOut || null,
|
||||
r.monitoringEnabled ? 1 : 0,
|
||||
r.backupEnabled ? 1 : 0,
|
||||
r.status ?? 'active',
|
||||
r.tariffType ?? '',
|
||||
r.currency ?? '',
|
||||
dailyRate,
|
||||
monthlyRate,
|
||||
r.createdAt ?? '',
|
||||
r.paidUntil ?? '',
|
||||
r.notes ?? '',
|
||||
userOverridesJson,
|
||||
id,
|
||||
)
|
||||
const row = db.prepare('SELECT * FROM vps WHERE id = ?').get(id)
|
||||
if (!row) return res.status(404).json({ error: 'Not found' })
|
||||
res.json(rowToVps(row))
|
||||
} catch (err) {
|
||||
res.status(500).json({ error: err.message })
|
||||
}
|
||||
})
|
||||
|
||||
router.delete('/:id', (req, res) => {
|
||||
try {
|
||||
const db = getDb()
|
||||
const { id } = req.params
|
||||
const result = db.prepare('DELETE FROM vps WHERE id = ?').run(id)
|
||||
if (result.changes === 0) return res.status(404).json({ error: 'Not found' })
|
||||
res.status(204).send()
|
||||
} catch (err) {
|
||||
res.status(500).json({ error: err.message })
|
||||
}
|
||||
})
|
||||
|
||||
router.patch('/bulk', (req, res) => {
|
||||
try {
|
||||
const db = getDb()
|
||||
const { ids = [], action, value } = req.body
|
||||
if (!Array.isArray(ids) || ids.length === 0) {
|
||||
return res.status(400).json({ error: 'ids must be a non-empty array' })
|
||||
}
|
||||
if (action === 'status' && value) {
|
||||
const validStatus = ['active', 'paused', 'archived']
|
||||
if (!validStatus.includes(value)) {
|
||||
return res.status(400).json({ error: 'value must be active, paused, or archived' })
|
||||
}
|
||||
const stmt = db.prepare('UPDATE vps SET status = ? WHERE id = ?')
|
||||
for (const id of ids) {
|
||||
stmt.run(value, id)
|
||||
}
|
||||
return res.json({ updated: ids.length, status: value })
|
||||
}
|
||||
if (action === 'delete') {
|
||||
const stmt = db.prepare('DELETE FROM vps WHERE id = ?')
|
||||
let deleted = 0
|
||||
for (const id of ids) {
|
||||
const result = stmt.run(id)
|
||||
if (result.changes > 0) deleted++
|
||||
}
|
||||
return res.json({ deleted })
|
||||
}
|
||||
if (action === 'project') {
|
||||
const projectValue = value == null ? '' : String(value)
|
||||
const { project: projName, projectId: projId } = projectColumnsForSave(db, projectValue)
|
||||
const getStmt = db.prepare('SELECT * FROM vps WHERE id = ?')
|
||||
const updStmt = db.prepare(
|
||||
'UPDATE vps SET project = ?, projectId = ?, userOverrides = ? WHERE id = ?',
|
||||
)
|
||||
let updated = 0
|
||||
for (const id of ids) {
|
||||
const existing = getStmt.get(id)
|
||||
if (!existing) continue
|
||||
if (
|
||||
String(existing.project ?? '') === projName &&
|
||||
String(existing.projectId ?? '') === String(projId ?? '')
|
||||
) {
|
||||
continue
|
||||
}
|
||||
let userOverrides = []
|
||||
try {
|
||||
userOverrides = existing.userOverrides ? JSON.parse(existing.userOverrides) : []
|
||||
} catch {
|
||||
userOverrides = []
|
||||
}
|
||||
if (!userOverrides.includes('project')) {
|
||||
userOverrides.push('project')
|
||||
}
|
||||
updStmt.run(projName, projId || null, JSON.stringify([...new Set(userOverrides)]), id)
|
||||
updated++
|
||||
}
|
||||
return res.json({ updated, project: projName, projectId: projId })
|
||||
}
|
||||
return res.status(400).json({ error: 'action must be status, delete, or project' })
|
||||
} catch (err) {
|
||||
res.status(500).json({ error: err.message })
|
||||
}
|
||||
})
|
||||
|
||||
export default router
|
||||
@@ -0,0 +1,83 @@
|
||||
import Fastify from 'fastify'
|
||||
import cors from '@fastify/cors'
|
||||
import sensible from '@fastify/sensible'
|
||||
import staticPlugin from '@fastify/static'
|
||||
import { existsSync } from 'node:fs'
|
||||
import { dirname, join } from 'node:path'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
|
||||
import { getDb } from '@cfdm/db'
|
||||
|
||||
import { dataRoutes } from './routes/data.js'
|
||||
import { vpsRoutes } from './routes/vps.js'
|
||||
import { providersRoutes } from './routes/providers.js'
|
||||
import { providerAccountsRoutes } from './routes/provider-accounts.js'
|
||||
import { paymentsRoutes } from './routes/payments.js'
|
||||
import { balanceLedgerRoutes } from './routes/balance-ledger.js'
|
||||
import { settingsRoutes } from './routes/settings.js'
|
||||
import { syncRoutes } from './routes/sync.js'
|
||||
import { projectsRoutes } from './routes/projects.js'
|
||||
import { backupRoutes } from './routes/backup.js'
|
||||
import { ratesProxyRoutes } from './routes/rates-proxy.js'
|
||||
|
||||
const __dirname = dirname(fileURLToPath(import.meta.url))
|
||||
|
||||
export interface BuildAppOptions {
|
||||
dbPath?: string
|
||||
staticDir?: string
|
||||
}
|
||||
|
||||
export async function buildApp(opts: BuildAppOptions = {}) {
|
||||
if (opts.dbPath) process.env.DB_PATH = opts.dbPath
|
||||
getDb()
|
||||
|
||||
const app = Fastify({
|
||||
logger: process.env.NODE_ENV !== 'production',
|
||||
})
|
||||
|
||||
await app.register(cors, { origin: true })
|
||||
await app.register(sensible)
|
||||
|
||||
await app.register(dataRoutes)
|
||||
await app.register(vpsRoutes)
|
||||
await app.register(providersRoutes)
|
||||
await app.register(providerAccountsRoutes)
|
||||
await app.register(paymentsRoutes)
|
||||
await app.register(balanceLedgerRoutes)
|
||||
await app.register(settingsRoutes)
|
||||
await app.register(syncRoutes)
|
||||
await app.register(projectsRoutes)
|
||||
await app.register(backupRoutes)
|
||||
await app.register(ratesProxyRoutes)
|
||||
|
||||
const staticDir = opts.staticDir ?? join(__dirname, '..', '..', 'web', 'dist')
|
||||
if (existsSync(staticDir)) {
|
||||
await app.register(staticPlugin, {
|
||||
root: staticDir,
|
||||
prefix: '/',
|
||||
wildcard: false,
|
||||
})
|
||||
app.setNotFoundHandler((req, reply) => {
|
||||
if (req.url.startsWith('/api')) {
|
||||
reply.code(404).send({ error: { code: 'NOT_FOUND', message: 'Not found' } })
|
||||
return
|
||||
}
|
||||
reply.sendFile('index.html')
|
||||
})
|
||||
}
|
||||
|
||||
return app
|
||||
}
|
||||
|
||||
async function start() {
|
||||
const port = Number(process.env.PORT ?? 3001)
|
||||
const app = await buildApp()
|
||||
try {
|
||||
await app.listen({ port, host: '0.0.0.0' })
|
||||
} catch (err) {
|
||||
app.log.error(err)
|
||||
process.exit(1)
|
||||
}
|
||||
}
|
||||
|
||||
void start()
|
||||
@@ -0,0 +1,44 @@
|
||||
import type { FastifyPluginAsync } from 'fastify'
|
||||
import { existsSync, readFileSync } from 'node:fs'
|
||||
import { getDbPath } from '@cfdm/db'
|
||||
import { getSnapshot } from '@cfdm/db/repositories/snapshot'
|
||||
|
||||
const BACKUP_VERSION = 1
|
||||
|
||||
export const backupRoutes: FastifyPluginAsync = async (app) => {
|
||||
app.get('/api/backup/json', async (_req, reply) => {
|
||||
const snapshot = { backupVersion: BACKUP_VERSION, exportedAt: new Date().toISOString(), ...getSnapshot() }
|
||||
reply.header('Content-Type', 'application/json; charset=utf-8')
|
||||
reply.header('Content-Disposition', 'attachment; filename="vps-tracker-backup.json"')
|
||||
return reply.send(JSON.stringify(snapshot, null, 2))
|
||||
})
|
||||
|
||||
app.get('/api/backup/database', async (_req, reply) => {
|
||||
const dbPath = getDbPath()
|
||||
if (!existsSync(dbPath)) {
|
||||
return reply.code(404).send({ error: { code: 'NOT_FOUND', message: 'Файл базы не найден' } })
|
||||
}
|
||||
const buf = readFileSync(dbPath)
|
||||
reply.header('Content-Type', 'application/octet-stream')
|
||||
reply.header('Content-Disposition', 'attachment; filename="vps-tracker.db"')
|
||||
return reply.send(buf)
|
||||
})
|
||||
|
||||
app.post('/api/backup/json', async (req, reply) => {
|
||||
const payload = req.body
|
||||
if (!payload || typeof payload !== 'object') {
|
||||
return reply.code(400).send({ error: { code: 'VALIDATION', message: 'Неверное тело запроса' } })
|
||||
}
|
||||
// TODO: implement JSON snapshot import via repositories
|
||||
return reply.code(501).send({ error: { code: 'NOT_IMPLEMENTED', message: 'JSON import pending migration' } })
|
||||
})
|
||||
|
||||
app.post('/api/backup/database', async (req, reply) => {
|
||||
const buf = req.body as Buffer
|
||||
if (!buf || !buf.length) {
|
||||
return reply.code(400).send({ error: { code: 'VALIDATION', message: 'Пустой файл' } })
|
||||
}
|
||||
// TODO: implement DB restore via better-sqlite3 backup API
|
||||
return reply.code(501).send({ error: { code: 'NOT_IMPLEMENTED', message: 'DB restore pending migration' } })
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
import type { FastifyPluginAsync } from 'fastify'
|
||||
import { balanceLedgerRepository } from '@cfdm/db/repositories/balance-ledger'
|
||||
import { balanceLedgerSchema } from '@cfdm/shared/contracts/balance-ledger'
|
||||
|
||||
export const balanceLedgerRoutes: FastifyPluginAsync = async (app) => {
|
||||
app.get('/api/balance-ledger', async () => balanceLedgerRepository.list())
|
||||
|
||||
app.post('/api/balance-ledger', async (req, reply) => {
|
||||
const parsed = balanceLedgerSchema.safeParse(req.body)
|
||||
if (!parsed.success) {
|
||||
return reply.code(400).send({ error: { code: 'VALIDATION', message: parsed.error.message } })
|
||||
}
|
||||
return reply.code(201).send(balanceLedgerRepository.create(parsed.data))
|
||||
})
|
||||
|
||||
app.put<{ Params: { id: string } }>('/api/balance-ledger/:id', async (req, reply) => {
|
||||
const parsed = balanceLedgerSchema.partial().safeParse(req.body)
|
||||
if (!parsed.success) {
|
||||
return reply.code(400).send({ error: { code: 'VALIDATION', message: parsed.error.message } })
|
||||
}
|
||||
const updated = balanceLedgerRepository.update(req.params.id, parsed.data)
|
||||
if (!updated) {
|
||||
return reply.code(404).send({ error: { code: 'NOT_FOUND', message: 'Not found' } })
|
||||
}
|
||||
return updated
|
||||
})
|
||||
|
||||
app.delete<{ Params: { id: string } }>('/api/balance-ledger/:id', async (req, reply) => {
|
||||
const ok = balanceLedgerRepository.delete(req.params.id)
|
||||
if (!ok) {
|
||||
return reply.code(404).send({ error: { code: 'NOT_FOUND', message: 'Not found' } })
|
||||
}
|
||||
return reply.code(204).send()
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
import type { FastifyPluginAsync } from 'fastify'
|
||||
import { getSnapshot } from '@cfdm/db/repositories/snapshot'
|
||||
|
||||
export const dataRoutes: FastifyPluginAsync = async (app) => {
|
||||
app.get('/api/data', async () => getSnapshot())
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
import type { FastifyPluginAsync } from 'fastify'
|
||||
import { paymentsRepository } from '@cfdm/db/repositories/payments'
|
||||
import { paymentSchema } from '@cfdm/shared/contracts/payment'
|
||||
|
||||
export const paymentsRoutes: FastifyPluginAsync = async (app) => {
|
||||
app.get('/api/payments', async () => paymentsRepository.list())
|
||||
|
||||
app.post('/api/payments', async (req, reply) => {
|
||||
const parsed = paymentSchema.safeParse(req.body)
|
||||
if (!parsed.success) {
|
||||
return reply.code(400).send({ error: { code: 'VALIDATION', message: parsed.error.message } })
|
||||
}
|
||||
return reply.code(201).send(paymentsRepository.create(parsed.data))
|
||||
})
|
||||
|
||||
app.put<{ Params: { id: string } }>('/api/payments/:id', async (req, reply) => {
|
||||
const parsed = paymentSchema.partial().safeParse(req.body)
|
||||
if (!parsed.success) {
|
||||
return reply.code(400).send({ error: { code: 'VALIDATION', message: parsed.error.message } })
|
||||
}
|
||||
const updated = paymentsRepository.update(req.params.id, parsed.data)
|
||||
if (!updated) {
|
||||
return reply.code(404).send({ error: { code: 'NOT_FOUND', message: 'Not found' } })
|
||||
}
|
||||
return updated
|
||||
})
|
||||
|
||||
app.delete<{ Params: { id: string } }>('/api/payments/:id', async (req, reply) => {
|
||||
const ok = paymentsRepository.delete(req.params.id)
|
||||
if (!ok) {
|
||||
return reply.code(404).send({ error: { code: 'NOT_FOUND', message: 'Not found' } })
|
||||
}
|
||||
return reply.code(204).send()
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
import type { FastifyPluginAsync } from 'fastify'
|
||||
import {
|
||||
projectsRepository,
|
||||
projectSuggestions,
|
||||
resolveOrCreateProject,
|
||||
normalizeProjectNameInput,
|
||||
} from '@cfdm/db/repositories/projects'
|
||||
|
||||
export const projectsRoutes: FastifyPluginAsync = async (app) => {
|
||||
app.get('/api/projects', async () => projectsRepository.list())
|
||||
|
||||
app.get('/api/projects/suggest', async (req) => {
|
||||
const q = (req.query as { q?: string })?.q ?? ''
|
||||
const limit = (req.query as { limit?: string })?.limit
|
||||
return projectSuggestions(q, limit ? Number(limit) : 20)
|
||||
})
|
||||
|
||||
app.post('/api/projects/resolve-or-create', async (req) => {
|
||||
const name = (req.body as { name?: unknown })?.name
|
||||
return resolveOrCreateProject(name)
|
||||
})
|
||||
|
||||
app.post('/api/projects', async (req, reply) => {
|
||||
const name = normalizeProjectNameInput((req.body as { name?: unknown })?.name)
|
||||
if (!name) {
|
||||
return reply.code(400).send({ error: { code: 'VALIDATION', message: 'name is required' } })
|
||||
}
|
||||
return reply.code(201).send(resolveOrCreateProject(name))
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
import type { FastifyPluginAsync } from 'fastify'
|
||||
import { providerAccountsRepository } from '@cfdm/db/repositories/provider-accounts'
|
||||
import { providerAccountSchema } from '@cfdm/shared/contracts/provider-account'
|
||||
|
||||
export const providerAccountsRoutes: FastifyPluginAsync = async (app) => {
|
||||
app.get('/api/provider-accounts', async () => providerAccountsRepository.list())
|
||||
|
||||
app.post('/api/provider-accounts', async (req, reply) => {
|
||||
const parsed = providerAccountSchema.safeParse(req.body)
|
||||
if (!parsed.success) {
|
||||
return reply.code(400).send({ error: { code: 'VALIDATION', message: parsed.error.message } })
|
||||
}
|
||||
const created = providerAccountsRepository.create(parsed.data)
|
||||
return reply.code(201).send(created)
|
||||
})
|
||||
|
||||
app.put<{ Params: { id: string } }>('/api/provider-accounts/:id', async (req, reply) => {
|
||||
const parsed = providerAccountSchema.partial().safeParse(req.body)
|
||||
if (!parsed.success) {
|
||||
return reply.code(400).send({ error: { code: 'VALIDATION', message: parsed.error.message } })
|
||||
}
|
||||
const updated = providerAccountsRepository.update(req.params.id, parsed.data)
|
||||
if (!updated) {
|
||||
return reply.code(404).send({ error: { code: 'NOT_FOUND', message: 'Not found' } })
|
||||
}
|
||||
return updated
|
||||
})
|
||||
|
||||
app.delete<{ Params: { id: string } }>('/api/provider-accounts/:id', async (req, reply) => {
|
||||
const ok = providerAccountsRepository.delete(req.params.id)
|
||||
if (!ok) {
|
||||
return reply.code(404).send({ error: { code: 'NOT_FOUND', message: 'Not found' } })
|
||||
}
|
||||
return reply.code(204).send()
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
import type { FastifyPluginAsync } from 'fastify'
|
||||
import { providersRepository } from '@cfdm/db/repositories/providers'
|
||||
import { providerSchema } from '@cfdm/shared/contracts/provider'
|
||||
|
||||
export const providersRoutes: FastifyPluginAsync = async (app) => {
|
||||
app.get('/api/providers', async () => providersRepository.list())
|
||||
|
||||
app.post('/api/providers', async (req, reply) => {
|
||||
const parsed = providerSchema.safeParse(req.body)
|
||||
if (!parsed.success) {
|
||||
return reply.code(400).send({ error: { code: 'VALIDATION', message: parsed.error.message } })
|
||||
}
|
||||
const created = providersRepository.create(parsed.data)
|
||||
return reply.code(201).send(created)
|
||||
})
|
||||
|
||||
app.put<{ Params: { id: string } }>('/api/providers/:id', async (req, reply) => {
|
||||
const parsed = providerSchema.partial().safeParse(req.body)
|
||||
if (!parsed.success) {
|
||||
return reply.code(400).send({ error: { code: 'VALIDATION', message: parsed.error.message } })
|
||||
}
|
||||
const updated = providersRepository.update(req.params.id, parsed.data)
|
||||
if (!updated) {
|
||||
return reply.code(404).send({ error: { code: 'NOT_FOUND', message: 'Not found' } })
|
||||
}
|
||||
return updated
|
||||
})
|
||||
|
||||
app.delete<{ Params: { id: string } }>('/api/providers/:id', async (req, reply) => {
|
||||
const ok = providersRepository.delete(req.params.id)
|
||||
if (!ok) {
|
||||
return reply.code(404).send({ error: { code: 'NOT_FOUND', message: 'Not found' } })
|
||||
}
|
||||
return reply.code(204).send()
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
import type { FastifyPluginAsync } from 'fastify'
|
||||
|
||||
export const ratesProxyRoutes: FastifyPluginAsync = async (app) => {
|
||||
app.get('/api/rates-proxy', async (req, reply) => {
|
||||
const url = (req.query as { url?: string })?.url
|
||||
if (!url) {
|
||||
return reply.code(400).send({ error: { code: 'VALIDATION', message: 'Missing url parameter' } })
|
||||
}
|
||||
try {
|
||||
const response = await fetch(url, { signal: AbortSignal.timeout(10_000) })
|
||||
if (!response.ok) {
|
||||
return reply.code(502).send({ error: { code: 'UPSTREAM', message: `Upstream returned ${response.status}` } })
|
||||
}
|
||||
return await response.json()
|
||||
} catch (err) {
|
||||
return reply.code(502).send({ error: { code: 'UPSTREAM', message: (err as Error).message || 'Failed to fetch rates' } })
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
import type { FastifyPluginAsync } from 'fastify'
|
||||
import { settingsRepository } from '@cfdm/db/repositories/settings'
|
||||
import { settingsSchema } from '@cfdm/shared/contracts/settings'
|
||||
|
||||
export const settingsRoutes: FastifyPluginAsync = async (app) => {
|
||||
app.get('/api/settings', async () => settingsRepository.list())
|
||||
|
||||
app.post('/api/settings', async (req, reply) => {
|
||||
const parsed = settingsSchema.safeParse(req.body)
|
||||
if (!parsed.success) {
|
||||
return reply.code(400).send({ error: { code: 'VALIDATION', message: parsed.error.message } })
|
||||
}
|
||||
const id = (req.body as { id?: string })?.id ?? 'settings-main'
|
||||
return reply.code(201).send(settingsRepository.upsert(id, parsed.data))
|
||||
})
|
||||
|
||||
app.put<{ Params: { id: string } }>('/api/settings/:id', async (req, reply) => {
|
||||
const parsed = settingsSchema.partial().safeParse(req.body)
|
||||
if (!parsed.success) {
|
||||
return reply.code(400).send({ error: { code: 'VALIDATION', message: parsed.error.message } })
|
||||
}
|
||||
return settingsRepository.upsert(req.params.id, parsed.data)
|
||||
})
|
||||
|
||||
app.post('/api/settings/telegram/test', async () => ({ ok: true }))
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
import type { FastifyPluginAsync } from 'fastify'
|
||||
import { desc } from 'drizzle-orm'
|
||||
import { getDb, schema } from '@cfdm/db'
|
||||
import { providerAccountsRepository } from '@cfdm/db/repositories/provider-accounts'
|
||||
import { providersRepository } from '@cfdm/db/repositories/providers'
|
||||
|
||||
interface SyncLogRow {
|
||||
id: string
|
||||
accountId: string
|
||||
startedAt: string
|
||||
finishedAt: string | null
|
||||
status: string | null
|
||||
vpsCount: number | null
|
||||
paymentsCount: number | null
|
||||
error: string | null
|
||||
summary: unknown
|
||||
}
|
||||
|
||||
function mapSyncLog(row: typeof schema.syncLog.$inferSelect): SyncLogRow {
|
||||
let summaryParsed: unknown = null
|
||||
if (row.summary) {
|
||||
try {
|
||||
summaryParsed = JSON.parse(row.summary)
|
||||
} catch {
|
||||
summaryParsed = null
|
||||
}
|
||||
}
|
||||
return {
|
||||
id: row.id,
|
||||
accountId: row.accountId,
|
||||
startedAt: row.startedAt,
|
||||
finishedAt: row.finishedAt,
|
||||
status: row.status,
|
||||
vpsCount: row.vpsCount,
|
||||
paymentsCount: row.paymentsCount,
|
||||
error: row.error,
|
||||
summary: summaryParsed,
|
||||
}
|
||||
}
|
||||
|
||||
export const syncRoutes: FastifyPluginAsync = async (app) => {
|
||||
app.get('/api/sync/status', async () => {
|
||||
const rows = getDb()
|
||||
.select()
|
||||
.from(schema.syncLog)
|
||||
.orderBy(desc(schema.syncLog.startedAt))
|
||||
.limit(50)
|
||||
.all()
|
||||
return rows.map(mapSyncLog)
|
||||
})
|
||||
|
||||
app.post<{ Params: { accountId: string } }>('/api/sync/:accountId', async (req, reply) => {
|
||||
const account = providerAccountsRepository.getWithCredentials(req.params.accountId)
|
||||
if (!account) {
|
||||
return reply.code(404).send({ error: { code: 'NOT_FOUND', message: 'Account not found' } })
|
||||
}
|
||||
const provider = account.providerId ? providersRepository.get(account.providerId) : undefined
|
||||
// TODO: port billmanager sync job
|
||||
return reply.code(501).send({
|
||||
accountId: req.params.accountId,
|
||||
provider: provider?.name ?? null,
|
||||
status: 'pending-migration',
|
||||
note: 'Sync job port pending migration from Express adapters',
|
||||
})
|
||||
})
|
||||
|
||||
app.get<{ Params: { accountId: string } }>('/api/sync/:accountId/balance', async (req, reply) => {
|
||||
const account = providerAccountsRepository.getWithCredentials(req.params.accountId)
|
||||
if (!account) {
|
||||
return reply.code(404).send({ error: { code: 'NOT_FOUND', message: 'Account not found' } })
|
||||
}
|
||||
// TODO: port fetchDashboardInfo
|
||||
return reply.code(501).send({
|
||||
accountId: req.params.accountId,
|
||||
status: 'pending-migration',
|
||||
note: 'Balance fetch pending migration from Express adapters',
|
||||
})
|
||||
})
|
||||
|
||||
app.post('/api/sync/test-connection', async (req, reply) => {
|
||||
const { apiBaseUrl, apiCredentials } = (req.body ?? {}) as {
|
||||
apiBaseUrl?: string
|
||||
apiCredentials?: string
|
||||
}
|
||||
if (!apiBaseUrl?.trim() || !apiCredentials?.trim()) {
|
||||
return reply.code(400).send({ error: { code: 'VALIDATION', message: 'Укажите URL и учётные данные' } })
|
||||
}
|
||||
// TODO: port testConnection
|
||||
return reply.code(501).send({
|
||||
ok: false,
|
||||
status: 'pending-migration',
|
||||
note: 'Connection test pending migration from Express adapters',
|
||||
})
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
import type { FastifyPluginAsync } from 'fastify'
|
||||
import { vpsRepository } from '@cfdm/db/repositories/vps'
|
||||
import { vpsSchema } from '@cfdm/shared/contracts/vps'
|
||||
|
||||
export const vpsRoutes: FastifyPluginAsync = async (app) => {
|
||||
app.get('/api/vps', async () => vpsRepository.list())
|
||||
|
||||
app.post('/api/vps', async (req, reply) => {
|
||||
const parsed = vpsSchema.safeParse(req.body)
|
||||
if (!parsed.success) {
|
||||
return reply.code(400).send({ error: { code: 'VALIDATION', message: parsed.error.message } })
|
||||
}
|
||||
return reply.code(201).send(vpsRepository.create(parsed.data))
|
||||
})
|
||||
|
||||
app.put<{ Params: { id: string } }>('/api/vps/:id', async (req, reply) => {
|
||||
const parsed = vpsSchema.partial().safeParse(req.body)
|
||||
if (!parsed.success) {
|
||||
return reply.code(400).send({ error: { code: 'VALIDATION', message: parsed.error.message } })
|
||||
}
|
||||
const updated = vpsRepository.update(req.params.id, parsed.data)
|
||||
if (!updated) {
|
||||
return reply.code(404).send({ error: { code: 'NOT_FOUND', message: 'Not found' } })
|
||||
}
|
||||
return updated
|
||||
})
|
||||
|
||||
app.delete<{ Params: { id: string } }>('/api/vps/:id', async (req, reply) => {
|
||||
const ok = vpsRepository.delete(req.params.id)
|
||||
if (!ok) {
|
||||
return reply.code(404).send({ error: { code: 'NOT_FOUND', message: 'Not found' } })
|
||||
}
|
||||
return reply.code(204).send()
|
||||
})
|
||||
|
||||
app.patch('/api/vps/bulk', async (req, reply) => {
|
||||
const body = req.body as { ids?: string[]; action?: string; value?: unknown }
|
||||
const ids = Array.isArray(body.ids) ? body.ids : []
|
||||
if (ids.length === 0) {
|
||||
return reply.code(400).send({ error: { code: 'VALIDATION', message: 'ids must be a non-empty array' } })
|
||||
}
|
||||
if (body.action === 'status') {
|
||||
const validStatus = ['active', 'paused', 'archived']
|
||||
const value = String(body.value ?? '')
|
||||
if (!validStatus.includes(value)) {
|
||||
return reply.code(400).send({ error: { code: 'VALIDATION', message: 'value must be active, paused, or archived' } })
|
||||
}
|
||||
return { updated: vpsRepository.bulkStatus(ids, value), status: value }
|
||||
}
|
||||
if (body.action === 'delete') {
|
||||
return { deleted: vpsRepository.bulkDelete(ids) }
|
||||
}
|
||||
if (body.action === 'project') {
|
||||
const value = body.value == null ? '' : String(body.value)
|
||||
return vpsRepository.bulkProject(ids, value)
|
||||
}
|
||||
return reply.code(400).send({ error: { code: 'VALIDATION', message: 'action must be status, delete, or project' } })
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
/**
|
||||
* Запуск синхронизации BILLmanager с записью в sync_log (для API и планировщика)
|
||||
*/
|
||||
|
||||
import { getDb } from './db.js'
|
||||
import { syncFromBillmanager } from './adapters/billmanager/index.js'
|
||||
|
||||
/**
|
||||
* @param {object} account - строка provider_accounts
|
||||
* @param {object} [opts] - { skipTariffs, skipVpsPayments }
|
||||
* @returns {Promise<object>} результат syncFromBillmanager + ok, logId
|
||||
*/
|
||||
export async function runBillmanagerAccountSync(account, opts = {}) {
|
||||
const db = getDb()
|
||||
const logId = `sync-${account.id}-${Date.now()}`
|
||||
db.prepare(`
|
||||
INSERT INTO sync_log (id, accountId, startedAt, status)
|
||||
VALUES (?, ?, ?, ?)
|
||||
`).run(logId, account.id, new Date().toISOString(), 'running')
|
||||
|
||||
try {
|
||||
const result = await syncFromBillmanager(account, db, opts)
|
||||
const summaryPayload = {
|
||||
...(result.syncSummary || {}),
|
||||
vpsCount: result.vpsCount,
|
||||
paymentsCount: result.paymentsCount,
|
||||
tariffsCount: result.tariffsCount ?? 0,
|
||||
}
|
||||
db.prepare(`
|
||||
UPDATE sync_log SET finishedAt=?, status=?, vpsCount=?, paymentsCount=?, summary=?
|
||||
WHERE id=?
|
||||
`).run(
|
||||
new Date().toISOString(),
|
||||
'ok',
|
||||
result.vpsCount,
|
||||
result.paymentsCount,
|
||||
JSON.stringify(summaryPayload),
|
||||
logId,
|
||||
)
|
||||
return { ok: true, logId, ...result }
|
||||
} catch (err) {
|
||||
db.prepare(`
|
||||
UPDATE sync_log SET finishedAt=?, status=?, error=?, summary=?
|
||||
WHERE id=?
|
||||
`).run(
|
||||
new Date().toISOString(),
|
||||
'error',
|
||||
err.message || 'Unknown error',
|
||||
JSON.stringify({ error: err.message || 'Unknown error' }),
|
||||
logId,
|
||||
)
|
||||
throw err
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,235 @@
|
||||
import { getDb } from './db.js'
|
||||
import { runBillmanagerAccountSync } from './sync-account-job.js'
|
||||
import { sendTelegramMessage } from './telegram.js'
|
||||
import { billmanagerAccountRowForSync } from './utils/billmanager-context.js'
|
||||
|
||||
let syncIntervalId = null
|
||||
let syncTariffsIntervalId = null
|
||||
|
||||
const UPCOMING_DAYS = 7
|
||||
|
||||
function getAccountBalance(accountId, providerAccounts, balanceLedger) {
|
||||
const account = providerAccounts.find((a) => a.id === accountId)
|
||||
if (account?.balance_api != null && Number.isFinite(Number(account.balance_api))) {
|
||||
return Number(account.balance_api)
|
||||
}
|
||||
const rows = balanceLedger.filter((row) => row.providerAccountId === accountId)
|
||||
const credits = rows
|
||||
.filter((row) => row.direction === 'credit')
|
||||
.reduce((acc, row) => acc + Number(row.amount || 0), 0)
|
||||
const debits = rows
|
||||
.filter((row) => row.direction === 'debit')
|
||||
.reduce((acc, row) => acc + Number(row.amount || 0), 0)
|
||||
return credits - debits
|
||||
}
|
||||
|
||||
function getPaidUntilDate(db, vps, providerAccounts, payments, balanceLedger, now) {
|
||||
if (vps.status !== 'active') return null
|
||||
const account = providerAccounts.find((a) => a.id === vps.providerAccountId)
|
||||
const tariffType = vps.tariffType || (Number(vps.dailyRate || 0) > 0 ? 'daily' : 'monthly')
|
||||
const isDailyBilling = tariffType === 'daily' || account?.billingMode === 'daily'
|
||||
|
||||
let paidUntilFromApi = null
|
||||
if (vps.paidUntil) {
|
||||
const d = new Date(vps.paidUntil)
|
||||
paidUntilFromApi = Number.isNaN(d.getTime()) ? null : d
|
||||
}
|
||||
|
||||
const isPaidUntilNextDay =
|
||||
paidUntilFromApi &&
|
||||
(() => {
|
||||
const today = new Date(now.getFullYear(), now.getMonth(), now.getDate())
|
||||
const diffMs = paidUntilFromApi - today
|
||||
const diffDays = Math.round(diffMs / (24 * 60 * 60 * 1000))
|
||||
return diffDays >= 0 && diffDays <= 2
|
||||
})()
|
||||
|
||||
const shouldCalculateFromBalance = isDailyBilling || isPaidUntilNextDay
|
||||
|
||||
if (!shouldCalculateFromBalance && paidUntilFromApi) return paidUntilFromApi
|
||||
|
||||
const dailyRate = Number(vps.dailyRate || 0)
|
||||
const monthlyRate = Number(vps.monthlyRate || 0)
|
||||
const burnRate = tariffType === 'daily' ? dailyRate : monthlyRate / 30
|
||||
if (!Number.isFinite(burnRate) || burnRate <= 0) return paidUntilFromApi
|
||||
|
||||
const accountBalance = getAccountBalance(vps.providerAccountId, providerAccounts, balanceLedger)
|
||||
const activeInAccount = db
|
||||
.prepare('SELECT id FROM vps WHERE providerAccountId = ? AND status = ?')
|
||||
.all(vps.providerAccountId, 'active').length
|
||||
const allocatedBalance = activeInAccount > 0 ? Math.max(0, accountBalance) / activeInAccount : 0
|
||||
const directPayments = payments
|
||||
.filter((p) => p.vpsId === vps.id && p.type === 'direct_vps_payment')
|
||||
.reduce((acc, p) => acc + Number(p.amount || 0), 0)
|
||||
const funds = directPayments + allocatedBalance
|
||||
const coveredDays = Math.floor(funds / burnRate)
|
||||
if (!Number.isFinite(coveredDays) || coveredDays <= 0) return paidUntilFromApi
|
||||
|
||||
const paidUntil = new Date(now)
|
||||
paidUntil.setDate(paidUntil.getDate() + coveredDays)
|
||||
return paidUntil
|
||||
}
|
||||
|
||||
async function sendPaymentExpiryNotifications(db) {
|
||||
const settings = db.prepare('SELECT * FROM settings WHERE id = ?').get('settings-main')
|
||||
if (!settings?.notifyPaymentExpiryEnabled || !settings?.telegramBotToken?.trim() || !settings?.telegramChatId?.trim()) {
|
||||
return
|
||||
}
|
||||
const vpsList = db.prepare('SELECT * FROM vps ORDER BY createdAt DESC').all()
|
||||
const providerAccounts = db.prepare('SELECT * FROM provider_accounts ORDER BY name').all()
|
||||
const payments = db.prepare('SELECT * FROM payments ORDER BY date DESC').all()
|
||||
const balanceLedger = db.prepare('SELECT * FROM balance_ledger ORDER BY date DESC').all()
|
||||
const providers = db.prepare('SELECT * FROM providers ORDER BY name').all()
|
||||
|
||||
const now = new Date()
|
||||
const threshold = new Date(now)
|
||||
threshold.setDate(threshold.getDate() + UPCOMING_DAYS)
|
||||
|
||||
const upcoming = []
|
||||
for (const vps of vpsList) {
|
||||
if (vps.status !== 'active') continue
|
||||
const paidUntil = getPaidUntilDate(db, vps, providerAccounts, payments, balanceLedger, now)
|
||||
if (!paidUntil || paidUntil > threshold || paidUntil < new Date(now.getFullYear(), now.getMonth(), now.getDate())) continue
|
||||
const provider = providers.find((p) => p.id === vps.providerId)
|
||||
upcoming.push({ vps, paidUntil, provider: provider?.name || '-' })
|
||||
}
|
||||
upcoming.sort((a, b) => a.paidUntil - b.paidUntil)
|
||||
|
||||
if (upcoming.length === 0) return
|
||||
|
||||
const lines = upcoming.slice(0, 10).map(({ vps, paidUntil, provider }) => {
|
||||
const dateStr = paidUntil.toLocaleDateString('ru-RU')
|
||||
return `• ${vps.dns || vps.ip} (${provider}) — до ${dateStr}`
|
||||
})
|
||||
const text = `⚠️ <b>Истекает оплата</b> (ближайшие ${UPCOMING_DAYS} дней):\n\n${lines.join('\n')}`
|
||||
await sendTelegramMessage(settings.telegramBotToken, settings.telegramChatId, text, settings.telegramMessageThreadId)
|
||||
}
|
||||
|
||||
export async function runScheduledSync() {
|
||||
try {
|
||||
const db = getDb()
|
||||
const settings = db.prepare('SELECT * FROM settings WHERE id = ?').get('settings-main')
|
||||
if (!settings?.syncEnabled) return
|
||||
const accountRows = db.prepare(`
|
||||
SELECT pa.* FROM provider_accounts pa
|
||||
INNER JOIN providers p ON p.id = pa.providerId
|
||||
WHERE lower(trim(COALESCE(p.apiType, ''))) = 'billmanager'
|
||||
AND length(trim(COALESCE(p.apiBaseUrl, ''))) > 0
|
||||
AND pa.apiCredentials IS NOT NULL AND length(trim(pa.apiCredentials)) > 0
|
||||
`).all()
|
||||
const providers = db.prepare('SELECT * FROM providers').all()
|
||||
const providerById = new Map(providers.map((p) => [p.id, p]))
|
||||
const accounts = accountRows
|
||||
.map((a) => billmanagerAccountRowForSync(a, providerById.get(a.providerId)))
|
||||
.filter(Boolean)
|
||||
|
||||
const digestLines = []
|
||||
const lowBalanceLines = []
|
||||
const token = settings?.telegramBotToken?.trim()
|
||||
const chatId = settings?.telegramChatId?.trim()
|
||||
const canTg = Boolean(token && chatId)
|
||||
|
||||
for (const account of accounts) {
|
||||
try {
|
||||
const result = await runBillmanagerAccountSync(account, { skipTariffs: true })
|
||||
const s = result.syncSummary || {}
|
||||
const parts = []
|
||||
if (s.added?.length) parts.push(`+${s.added.length} VPS`)
|
||||
if (s.updated?.length) parts.push(`изм. ${s.updated.length}`)
|
||||
if (result.paymentsCount) parts.push(`платежи +${result.paymentsCount}`)
|
||||
digestLines.push(`✓ ${account.name}: ${parts.length ? parts.join(', ') : 'без изменений'}`)
|
||||
|
||||
const apiBal = result.balance?.balance
|
||||
const threshold = account.balance_alert_below
|
||||
if (
|
||||
canTg &&
|
||||
settings.notifyLowBalanceEnabled &&
|
||||
threshold != null &&
|
||||
Number.isFinite(Number(threshold)) &&
|
||||
apiBal != null &&
|
||||
Number.isFinite(Number(apiBal)) &&
|
||||
Number(apiBal) < Number(threshold)
|
||||
) {
|
||||
const cur = result.balance?.currency || account.balance_currency || account.currency || ''
|
||||
lowBalanceLines.push(
|
||||
`• ${account.name}: ${apiBal} ${cur} (порог ${threshold})`,
|
||||
)
|
||||
}
|
||||
} catch (err) {
|
||||
digestLines.push(`✗ ${account.name}: ${err.message || 'ошибка'}`)
|
||||
}
|
||||
}
|
||||
|
||||
if (canTg && settings.notifySyncDigestEnabled && digestLines.length > 0) {
|
||||
const text = `📋 <b>Синхронизация VPS</b>\n\n${digestLines.join('\n')}`
|
||||
await sendTelegramMessage(token, chatId, text, settings.telegramMessageThreadId)
|
||||
}
|
||||
if (canTg && settings.notifyLowBalanceEnabled && lowBalanceLines.length > 0) {
|
||||
const text = `💰 <b>Низкий баланс</b>\n\n${lowBalanceLines.join('\n')}`
|
||||
await sendTelegramMessage(token, chatId, text, settings.telegramMessageThreadId)
|
||||
}
|
||||
|
||||
if (settings?.notifyPaymentExpiryEnabled) {
|
||||
await sendPaymentExpiryNotifications(db)
|
||||
}
|
||||
} catch (err) {
|
||||
console.warn('Scheduled sync error:', err.message)
|
||||
}
|
||||
}
|
||||
|
||||
export async function runScheduledSyncTariffs() {
|
||||
try {
|
||||
const db = getDb()
|
||||
const settings = db.prepare('SELECT * FROM settings WHERE id = ?').get('settings-main')
|
||||
if (!settings?.syncEnabled) return
|
||||
const accountRows = db.prepare(`
|
||||
SELECT pa.* FROM provider_accounts pa
|
||||
INNER JOIN providers p ON p.id = pa.providerId
|
||||
WHERE lower(trim(COALESCE(p.apiType, ''))) = 'billmanager'
|
||||
AND length(trim(COALESCE(p.apiBaseUrl, ''))) > 0
|
||||
AND pa.apiCredentials IS NOT NULL AND length(trim(pa.apiCredentials)) > 0
|
||||
`).all()
|
||||
const providers = db.prepare('SELECT * FROM providers ORDER BY name').all()
|
||||
const providerById = new Map(providers.map((p) => [p.id, p]))
|
||||
const accounts = accountRows
|
||||
.map((a) => billmanagerAccountRowForSync(a, providerById.get(a.providerId)))
|
||||
.filter(Boolean)
|
||||
|
||||
for (const account of accounts) {
|
||||
try {
|
||||
const result = await runBillmanagerAccountSync(account, { skipVpsPayments: true })
|
||||
const newTariffs = result?.newTariffs || []
|
||||
if (newTariffs.length > 0 && settings?.notifyNewTariffsEnabled && settings?.telegramBotToken?.trim() && settings?.telegramChatId?.trim()) {
|
||||
const provider = providers.find((p) => p.id === account.providerId)
|
||||
const providerName = provider?.name || account.name || '-'
|
||||
const lines = newTariffs.slice(0, 15).map((t) => `• ${t.name || '—'} — ${t.price || '—'}`)
|
||||
const text = `🆕 <b>Новые тарифы</b> (${providerName}):\n\n${lines.join('\n')}`
|
||||
await sendTelegramMessage(settings.telegramBotToken, settings.telegramChatId, text, settings.telegramMessageThreadId)
|
||||
}
|
||||
} catch (err) {
|
||||
console.warn(`Sync tariffs failed for account ${account.id}:`, err.message)
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
console.warn('Scheduled sync tariffs error:', err.message)
|
||||
}
|
||||
}
|
||||
|
||||
export function startScheduler() {
|
||||
if (syncIntervalId) clearInterval(syncIntervalId)
|
||||
syncIntervalId = null
|
||||
if (syncTariffsIntervalId) clearInterval(syncTariffsIntervalId)
|
||||
syncTariffsIntervalId = null
|
||||
try {
|
||||
const db = getDb()
|
||||
const settings = db.prepare('SELECT * FROM settings WHERE id = ?').get('settings-main')
|
||||
if (!settings?.syncEnabled) return
|
||||
const interval = Math.max(15, Number(settings.syncIntervalMinutes) || 60)
|
||||
const tariffsInterval = Math.max(60, Number(settings.syncTariffsIntervalMinutes) || 1440)
|
||||
syncIntervalId = setInterval(runScheduledSync, interval * 60 * 1000)
|
||||
syncTariffsIntervalId = setInterval(runScheduledSyncTariffs, tariffsInterval * 60 * 1000)
|
||||
console.log(`Scheduled sync enabled: VPS/payments every ${interval} min, tariffs every ${tariffsInterval} min`)
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
/**
|
||||
* Telegram Bot API — отправка уведомлений
|
||||
*/
|
||||
|
||||
/**
|
||||
* @param {string} token - Bot token from @BotFather
|
||||
* @param {string|string[]} chatIds - Chat ID(s), comma-separated string or array
|
||||
* @param {string} text - Message text
|
||||
* @param {string|number} [messageThreadId] - ID топика в SuperGroup (для отправки в цепочку сообщений)
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
export async function sendTelegramMessage(token, chatIds, text, messageThreadId) {
|
||||
if (!token?.trim() || !text?.trim()) return
|
||||
const ids = Array.isArray(chatIds)
|
||||
? chatIds
|
||||
: String(chatIds || '')
|
||||
.split(',')
|
||||
.map((id) => id.trim())
|
||||
.filter(Boolean)
|
||||
if (ids.length === 0) return
|
||||
|
||||
const threadId = messageThreadId != null && messageThreadId !== '' ? Number(messageThreadId) : null
|
||||
const payload = {
|
||||
text,
|
||||
parse_mode: 'HTML',
|
||||
disable_web_page_preview: true,
|
||||
}
|
||||
if (Number.isFinite(threadId)) payload.message_thread_id = threadId
|
||||
|
||||
const url = `https://api.telegram.org/bot${token.trim()}/sendMessage`
|
||||
for (const chatId of ids) {
|
||||
try {
|
||||
const res = await fetch(url, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
...payload,
|
||||
chat_id: chatId,
|
||||
}),
|
||||
})
|
||||
const data = await res.json().catch(() => ({}))
|
||||
if (!data.ok) {
|
||||
console.warn(`Telegram sendMessage failed for chat ${chatId}:`, data.description || res.statusText)
|
||||
}
|
||||
} catch (err) {
|
||||
console.warn(`Telegram sendMessage error for chat ${chatId}:`, err.message)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
{
|
||||
"extends": "../../tsconfig.base.json",
|
||||
"compilerOptions": {
|
||||
"module": "NodeNext",
|
||||
"moduleResolution": "NodeNext",
|
||||
"target": "ES2022",
|
||||
"outDir": "./dist",
|
||||
"rootDir": "./src",
|
||||
"noEmit": false,
|
||||
"verbatimModuleSyntax": false,
|
||||
"types": ["node"]
|
||||
},
|
||||
"include": ["src/**/*.ts"]
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
/**
|
||||
* BILLmanager: URL и тип API задаются на хостере (providers), учётные данные — на аккаунте.
|
||||
* Поддержка fallback на поля аккаунта для старых данных до миграции.
|
||||
*/
|
||||
|
||||
/**
|
||||
* @param {object|null|undefined} accountRow
|
||||
* @param {object|null|undefined} providerRow
|
||||
* @returns {{ apiType: string, apiBaseUrl: string }}
|
||||
*/
|
||||
export function resolveBillmanagerApi(accountRow, providerRow) {
|
||||
const apiType = String(providerRow?.apiType || accountRow?.apiType || '').trim()
|
||||
const apiBaseUrl = String(providerRow?.apiBaseUrl || accountRow?.apiBaseUrl || '').trim()
|
||||
return { apiType, apiBaseUrl }
|
||||
}
|
||||
|
||||
/**
|
||||
* Объект аккаунта с подставленным URL для syncFromBillmanager / balance.
|
||||
* @param {object} accountRow
|
||||
* @param {object|null|undefined} providerRow
|
||||
* @returns {object|null} null если не готово к запросам API
|
||||
*/
|
||||
export function billmanagerAccountRowForSync(accountRow, providerRow) {
|
||||
if (!accountRow) return null
|
||||
const { apiType, apiBaseUrl } = resolveBillmanagerApi(accountRow, providerRow)
|
||||
const cred = String(accountRow.apiCredentials || '').trim()
|
||||
if (apiType !== 'billmanager' || !apiBaseUrl || !cred) return null
|
||||
return { ...accountRow, apiType: 'billmanager', apiBaseUrl }
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
/**
|
||||
* Map database rows to API response format
|
||||
*/
|
||||
|
||||
/**
|
||||
* @param {object} row - provider_account row
|
||||
* @returns {object} sanitized (apiCredentials hidden)
|
||||
*/
|
||||
export function sanitizeAccount(row) {
|
||||
if (!row) return row
|
||||
const { apiCredentials, ...rest } = row
|
||||
return { ...rest, apiCredentialsSet: Boolean(apiCredentials) }
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {object} row - active_tariffs row
|
||||
* @returns {object|null}
|
||||
*/
|
||||
export function rowToActiveTariff(row) {
|
||||
if (!row) return null
|
||||
return {
|
||||
...row,
|
||||
orderAvailable: Boolean(row.orderAvailable),
|
||||
ramGb: row.ramGb != null ? Number(row.ramGb) : 0,
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {object} row - tariff_sync_options row
|
||||
* @returns {object|null}
|
||||
*/
|
||||
export function rowToTariffSyncOptions(row) {
|
||||
if (!row) return null
|
||||
let datacenters = []
|
||||
let periods = []
|
||||
try {
|
||||
datacenters = row.datacenters ? JSON.parse(row.datacenters) : []
|
||||
} catch {
|
||||
/* ignore parse error */
|
||||
}
|
||||
try {
|
||||
periods = row.periods ? JSON.parse(row.periods) : []
|
||||
} catch {
|
||||
/* ignore parse error */
|
||||
}
|
||||
return {
|
||||
...row,
|
||||
datacenters: Array.isArray(datacenters) ? datacenters : [],
|
||||
periods: Array.isArray(periods) ? periods : [],
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user