cs-prices: full ByMykel catalog, every config, daily multi-source prices, item pages with working charts
All checks were successful
Deploy production / deploy (push) Successful in 1m18s
All checks were successful
Deploy production / deploy (push) Successful in 1m18s
- cs.skins catalog (weapons, knives, gloves, stickers, cases, agents, charms, …) refreshed weekly - every market config: wears in float range, StatTrak, Souvenir, Doppler/Gamma phases - cs.daily_prices (one row per config/stream/day, idempotent) from Skinport, Steam, CSFloat, Buff163 - cs.price_windows for 24h/7d/30d/90d sale aggregates, cs.fx_rates (ECB) - scripts/cs-prices.ts daily|catalog|prices; legacy ingest fixed for the new unique index - skin browser + /projects/cs-prices/[slug] with variant/wear/phase switcher and real charts - charts show points for short histories and pad sparse time axes
This commit is contained in:
@@ -2,13 +2,30 @@
|
||||
import { onMount } from 'svelte';
|
||||
import type { ECharts } from 'echarts/core';
|
||||
|
||||
export type PriceSeries = { key: string; name: string; points: [number, number][] };
|
||||
let { series, kind, currency }: { series: PriceSeries[]; kind: string; currency: string } =
|
||||
$props();
|
||||
export type PriceSeries = {
|
||||
key: string;
|
||||
name: string;
|
||||
points: [number, number][];
|
||||
color?: string;
|
||||
dashed?: boolean;
|
||||
};
|
||||
let {
|
||||
series,
|
||||
kind,
|
||||
currency,
|
||||
height = 'min(62vh, 560px)',
|
||||
zoom = true
|
||||
}: {
|
||||
series: PriceSeries[];
|
||||
kind: string;
|
||||
currency: string;
|
||||
height?: string;
|
||||
zoom?: boolean;
|
||||
} = $props();
|
||||
let element: HTMLDivElement;
|
||||
let chart: ECharts | undefined;
|
||||
let ready = $state(false);
|
||||
let money = $derived(new Intl.NumberFormat('en-US', { style: 'currency', currency }));
|
||||
let money = $derived(new Intl.NumberFormat('nl-NL', { style: 'currency', currency }));
|
||||
const escapeHtml = (value: string) =>
|
||||
value.replace(
|
||||
/[&<>"']/g,
|
||||
@@ -22,15 +39,53 @@
|
||||
const foreground = style.getPropertyValue('--site-text').trim();
|
||||
const muted = style.getPropertyValue('--site-muted').trim();
|
||||
const border = style.getPropertyValue('--site-border').trim();
|
||||
const dark = style.getPropertyValue('--site-bg').trim() === '#000';
|
||||
const many = series.length > 100;
|
||||
const legend = series.length > 1 && series.length <= 12;
|
||||
const surface = style.getPropertyValue('--site-surface').trim();
|
||||
// A few days of daily data would otherwise be stretched into hour ticks; pad to a week.
|
||||
let first = Infinity;
|
||||
let last = -Infinity;
|
||||
for (const line of series)
|
||||
for (const [t] of line.points) {
|
||||
if (t < first) first = t;
|
||||
if (t > last) last = t;
|
||||
}
|
||||
const day = 86_400_000;
|
||||
const short = Number.isFinite(first) && last - first < 7 * day;
|
||||
const pad = short ? (7 * day - (last - first)) / 2 : 0;
|
||||
chart.setOption(
|
||||
{
|
||||
animation: false,
|
||||
backgroundColor: 'transparent',
|
||||
grid: { left: 78, right: 20, top: 28, bottom: 72 },
|
||||
grid: {
|
||||
left: 64,
|
||||
right: 14,
|
||||
top: legend ? 40 : 20,
|
||||
bottom: zoom ? 64 : 28,
|
||||
containLabel: false
|
||||
},
|
||||
legend: legend
|
||||
? {
|
||||
top: 0,
|
||||
left: 0,
|
||||
icon: 'roundRect',
|
||||
itemWidth: 10,
|
||||
itemHeight: 4,
|
||||
textStyle: { color: muted, fontSize: 11 }
|
||||
}
|
||||
: { show: false },
|
||||
xAxis: {
|
||||
type: 'time',
|
||||
min: short ? first - pad : undefined,
|
||||
max: short ? last + pad : undefined,
|
||||
minInterval: day,
|
||||
axisLine: { lineStyle: { color: border } },
|
||||
axisLabel: { color: muted },
|
||||
axisLabel: {
|
||||
color: muted,
|
||||
hideOverlap: true,
|
||||
formatter: { year: '{yyyy}', month: '{MMM}', day: '{d} {MMM}', hour: '{d} {MMM}' }
|
||||
},
|
||||
splitLine: { show: false }
|
||||
},
|
||||
yAxis: {
|
||||
@@ -39,44 +94,71 @@
|
||||
axisLabel: { color: muted, formatter: (value: number) => money.format(value / 100) },
|
||||
splitLine: { lineStyle: { color: border } }
|
||||
},
|
||||
dataZoom: [
|
||||
{ type: 'inside' },
|
||||
{
|
||||
type: 'slider',
|
||||
bottom: 12,
|
||||
height: 18,
|
||||
borderColor: border,
|
||||
textStyle: { color: muted },
|
||||
fillerColor: 'rgba(127,127,127,.15)'
|
||||
}
|
||||
],
|
||||
tooltip:
|
||||
series.length > 100
|
||||
? { show: false }
|
||||
dataZoom: zoom
|
||||
? [
|
||||
{ type: 'inside' },
|
||||
{
|
||||
type: 'slider',
|
||||
bottom: 10,
|
||||
height: 18,
|
||||
borderColor: border,
|
||||
textStyle: { color: muted },
|
||||
fillerColor: 'rgba(127,127,127,.15)'
|
||||
}
|
||||
]
|
||||
: [],
|
||||
tooltip: many
|
||||
? { show: false }
|
||||
: legend || series.length === 1
|
||||
? {
|
||||
trigger: 'axis',
|
||||
backgroundColor: surface,
|
||||
borderColor: border,
|
||||
textStyle: { color: foreground, fontSize: 12 },
|
||||
formatter: (
|
||||
params: {
|
||||
seriesName: string;
|
||||
value: [number, number];
|
||||
color: string;
|
||||
}[]
|
||||
) =>
|
||||
params.length
|
||||
? `${new Date(params[0].value[0]).toLocaleDateString('nl-NL')}<br>` +
|
||||
params
|
||||
.map(
|
||||
(p) =>
|
||||
`<span style="color:${p.color}">●</span> ${escapeHtml(p.seriesName)} · <b>${money.format(p.value[1] / 100)}</b>`
|
||||
)
|
||||
.join('<br>')
|
||||
: ''
|
||||
}
|
||||
: {
|
||||
trigger: 'item',
|
||||
backgroundColor: style.getPropertyValue('--site-surface').trim(),
|
||||
backgroundColor: surface,
|
||||
borderColor: border,
|
||||
textStyle: { color: foreground },
|
||||
formatter: (params: { seriesName: string; value: [number, number] }) =>
|
||||
`${escapeHtml(params.seriesName)}<br>${new Date(params.value[0]).toLocaleDateString()} · ${money.format(params.value[1] / 100)}`
|
||||
`${escapeHtml(params.seriesName)}<br>${new Date(params.value[0]).toLocaleDateString('nl-NL')} · ${money.format(params.value[1] / 100)}`
|
||||
},
|
||||
series: series.map((item, index) => ({
|
||||
name: item.name,
|
||||
type: 'line',
|
||||
data: item.points,
|
||||
showSymbol: false,
|
||||
// Few points (a new archive, or one sweep) would be invisible as a bare line.
|
||||
showSymbol: item.points.length <= 60,
|
||||
symbolSize: item.points.length <= 3 ? 7 : 4,
|
||||
connectNulls: false,
|
||||
silent: series.length > 100,
|
||||
silent: many,
|
||||
lineStyle: {
|
||||
width: series.length > 100 ? 0.7 : 1.8,
|
||||
opacity: series.length > 100 ? 0.42 : 0.9
|
||||
width: many ? 0.7 : 1.8,
|
||||
opacity: many ? 0.42 : 0.9,
|
||||
type: item.dashed ? 'dashed' : 'solid'
|
||||
},
|
||||
itemStyle: {
|
||||
color: `hsl(${(index * 137.508) % 360} 65% ${style.getPropertyValue('--site-bg').trim() === '#000' ? '68%' : '38%'})`
|
||||
color: item.color ?? `hsl(${(index * 137.508) % 360} 65% ${dark ? '68%' : '38%'})`
|
||||
},
|
||||
emphasis: { focus: 'series', lineStyle: { width: 3, opacity: 1 } },
|
||||
large: true
|
||||
large: many
|
||||
}))
|
||||
},
|
||||
true
|
||||
@@ -90,7 +172,7 @@
|
||||
import('echarts/core').then(async (echarts) => {
|
||||
const [
|
||||
{ LineChart },
|
||||
{ GridComponent, TooltipComponent, DataZoomComponent },
|
||||
{ GridComponent, TooltipComponent, DataZoomComponent, LegendComponent },
|
||||
{ CanvasRenderer }
|
||||
] = await Promise.all([
|
||||
import('echarts/charts'),
|
||||
@@ -98,7 +180,14 @@
|
||||
import('echarts/renderers')
|
||||
]);
|
||||
if (disposed) return;
|
||||
echarts.use([LineChart, GridComponent, TooltipComponent, DataZoomComponent, CanvasRenderer]);
|
||||
echarts.use([
|
||||
LineChart,
|
||||
GridComponent,
|
||||
TooltipComponent,
|
||||
DataZoomComponent,
|
||||
LegendComponent,
|
||||
CanvasRenderer
|
||||
]);
|
||||
chart = echarts.init(element, undefined, { renderer: 'canvas' });
|
||||
ready = true;
|
||||
update();
|
||||
@@ -107,7 +196,7 @@
|
||||
theme = new MutationObserver(update);
|
||||
theme.observe(document.documentElement, {
|
||||
attributes: true,
|
||||
attributeFilter: ['data-theme']
|
||||
attributeFilter: ['data-theme', 'class']
|
||||
});
|
||||
});
|
||||
return () => {
|
||||
@@ -118,12 +207,16 @@
|
||||
};
|
||||
});
|
||||
$effect(() => {
|
||||
// Track the props so a new selection redraws.
|
||||
void series;
|
||||
void currency;
|
||||
if (ready) update();
|
||||
});
|
||||
</script>
|
||||
|
||||
<div
|
||||
class="chart"
|
||||
style:height
|
||||
bind:this={element}
|
||||
role="img"
|
||||
aria-label={`${series.length} ${kind} price series chart`}
|
||||
@@ -132,7 +225,6 @@
|
||||
<style>
|
||||
.chart {
|
||||
width: 100%;
|
||||
height: min(62vh, 560px);
|
||||
min-height: 320px;
|
||||
min-height: 260px;
|
||||
}
|
||||
</style>
|
||||
|
||||
43
src/lib/cs-prices/catalog.test.ts
Normal file
43
src/lib/cs-prices/catalog.test.ts
Normal file
@@ -0,0 +1,43 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { configRank, parseConfig, slugify } from './catalog';
|
||||
|
||||
describe('parseConfig', () => {
|
||||
it('splits knives, StatTrak and wear', () => {
|
||||
expect(parseConfig('★ StatTrak™ Karambit | Doppler (Factory New)')).toEqual({
|
||||
starred: true,
|
||||
stattrak: true,
|
||||
souvenir: false,
|
||||
wear: 'Factory New',
|
||||
base: 'Karambit | Doppler',
|
||||
display: '★ Karambit | Doppler'
|
||||
});
|
||||
});
|
||||
it('handles souvenirs and wearless items', () => {
|
||||
expect(parseConfig('Souvenir AWP | Dragon Lore (Field-Tested)').souvenir).toBe(true);
|
||||
expect(parseConfig('Souvenir AWP | Dragon Lore (Field-Tested)').base).toBe('AWP | Dragon Lore');
|
||||
expect(parseConfig('Sticker | Heroic (Holo) | Rio 2022').base).toBe(
|
||||
'Sticker | Heroic (Holo) | Rio 2022'
|
||||
);
|
||||
expect(parseConfig('Paris 2023 Mirage Souvenir Package').souvenir).toBe(false);
|
||||
expect(parseConfig('StatTrak™ Music Kit | Daniel Sadowski, Crimson Assault').base).toBe(
|
||||
'Music Kit | Daniel Sadowski, Crimson Assault'
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('slugify', () => {
|
||||
it('makes stable slugs', () => {
|
||||
expect(slugify('★ Karambit | Doppler')).toBe('karambit-doppler');
|
||||
expect(slugify('AK-47 | Redline')).toBe('ak-47-redline');
|
||||
});
|
||||
});
|
||||
|
||||
describe('configRank', () => {
|
||||
it('sorts normal, then StatTrak, by wear and phase', () => {
|
||||
const a = configRank({ stattrak: false, souvenir: false, wear: 'Factory New', phase: 'Ruby' });
|
||||
const b = configRank({ stattrak: false, souvenir: false, wear: 'Minimal Wear', phase: null });
|
||||
const c = configRank({ stattrak: true, souvenir: false, wear: 'Factory New', phase: null });
|
||||
expect(a).toBeLessThan(b);
|
||||
expect(b).toBeLessThan(c);
|
||||
});
|
||||
});
|
||||
87
src/lib/cs-prices/catalog.ts
Normal file
87
src/lib/cs-prices/catalog.ts
Normal file
@@ -0,0 +1,87 @@
|
||||
// Pure helpers shared by scripts/cs-prices.ts and the item pages: how a market hash name maps to
|
||||
// its skin (the page that groups every wear, StatTrak, Souvenir and phase config).
|
||||
|
||||
export const wearOrder = [
|
||||
'Factory New',
|
||||
'Minimal Wear',
|
||||
'Field-Tested',
|
||||
'Well-Worn',
|
||||
'Battle-Scarred'
|
||||
] as const;
|
||||
export const wearShort: Record<string, string> = {
|
||||
'Factory New': 'FN',
|
||||
'Minimal Wear': 'MW',
|
||||
'Field-Tested': 'FT',
|
||||
'Well-Worn': 'WW',
|
||||
'Battle-Scarred': 'BS'
|
||||
};
|
||||
export const phaseOrder = [
|
||||
'Phase 1',
|
||||
'Phase 2',
|
||||
'Phase 3',
|
||||
'Phase 4',
|
||||
'Ruby',
|
||||
'Sapphire',
|
||||
'Black Pearl',
|
||||
'Emerald'
|
||||
] as const;
|
||||
|
||||
const wearSuffix = / \((Factory New|Minimal Wear|Field-Tested|Well-Worn|Battle-Scarred)\)$/;
|
||||
|
||||
export type Config = {
|
||||
starred: boolean;
|
||||
stattrak: boolean;
|
||||
souvenir: boolean;
|
||||
wear: string | null;
|
||||
/** Name without ★, StatTrak™, Souvenir or wear: the skin grouping key. */
|
||||
base: string;
|
||||
/** Display name of the skin: base with ★ for knives and gloves. */
|
||||
display: string;
|
||||
};
|
||||
|
||||
export function parseConfig(marketHashName: string): Config {
|
||||
let name = marketHashName.trim();
|
||||
const starred = name.startsWith('★ ');
|
||||
if (starred) name = name.slice(2);
|
||||
let stattrak = false;
|
||||
let souvenir = false;
|
||||
if (name.startsWith('StatTrak™ ')) {
|
||||
stattrak = true;
|
||||
name = name.slice('StatTrak™ '.length);
|
||||
}
|
||||
if (name.startsWith('Souvenir ') && name.includes(' | ')) {
|
||||
souvenir = true;
|
||||
name = name.slice('Souvenir '.length);
|
||||
}
|
||||
const wear = wearSuffix.exec(name)?.[1] ?? null;
|
||||
if (wear) name = name.replace(wearSuffix, '');
|
||||
return { starred, stattrak, souvenir, wear, base: name, display: starred ? `★ ${name}` : name };
|
||||
}
|
||||
|
||||
export function slugify(value: string) {
|
||||
return (
|
||||
value
|
||||
.normalize('NFKD')
|
||||
.replace(/[\u0300-\u036f]/g, '')
|
||||
.replace(/★/g, '')
|
||||
.replace(/™/g, '')
|
||||
.toLowerCase()
|
||||
.replace(/&/g, ' and ')
|
||||
.replace(/[^a-z0-9]+/g, '-')
|
||||
.replace(/^-+|-+$/g, '')
|
||||
.slice(0, 120) || 'item'
|
||||
);
|
||||
}
|
||||
|
||||
/** Order configs: normal before StatTrak before Souvenir, then wear, then phase. */
|
||||
export function configRank(row: {
|
||||
stattrak: boolean;
|
||||
souvenir: boolean;
|
||||
wear: string | null;
|
||||
phase: string | null;
|
||||
}) {
|
||||
const variant = row.souvenir ? 2 : row.stattrak ? 1 : 0;
|
||||
const wear = row.wear ? wearOrder.indexOf(row.wear as (typeof wearOrder)[number]) + 1 : 0;
|
||||
const phase = row.phase ? phaseOrder.indexOf(row.phase as (typeof phaseOrder)[number]) + 1 : 0;
|
||||
return variant * 1000 + wear * 20 + phase;
|
||||
}
|
||||
275
src/lib/server/cs-prices.ts
Normal file
275
src/lib/server/cs-prices.ts
Normal file
@@ -0,0 +1,275 @@
|
||||
import { db } from '#lib/server/db/index.js';
|
||||
import { sql } from 'drizzle-orm';
|
||||
import { configRank, wearOrder, wearShort } from '#lib/cs-prices/catalog.js';
|
||||
|
||||
// Read side of the CS2 price archive (cs.*): skin search, a skin's configs with their latest
|
||||
// price per source, and one config's daily history. USD streams are shown in EUR using the
|
||||
// ECB rate of that day (cs.fx_rates); `native` keeps the source's own currency.
|
||||
|
||||
export type Stream = { id: number; source: string; currency: string; kind: string; label: string };
|
||||
|
||||
export const kinds = [
|
||||
['weapon', 'Weapons'],
|
||||
['knife', 'Knives'],
|
||||
['gloves', 'Gloves'],
|
||||
['sticker', 'Stickers'],
|
||||
['container', 'Cases'],
|
||||
['agent', 'Agents'],
|
||||
['charm', 'Charms'],
|
||||
['patch', 'Patches'],
|
||||
['music-kit', 'Music kits'],
|
||||
['graffiti', 'Graffiti'],
|
||||
['collectible', 'Pins & coins'],
|
||||
['key', 'Keys']
|
||||
] as const;
|
||||
|
||||
export async function streams(): Promise<Stream[]> {
|
||||
const rows = await db.execute(sql`SELECT id, source, currency, kind,
|
||||
coalesce(label, source || ' ' || replace(kind, '-', ' ')) AS label
|
||||
FROM cs.price_streams WHERE id IS NOT NULL ORDER BY id`);
|
||||
return (rows as unknown as Stream[]).map((row) => ({ ...row, id: Number(row.id) }));
|
||||
}
|
||||
|
||||
export async function overview() {
|
||||
const [row] = (await db.execute(sql`SELECT
|
||||
(SELECT count(*)::int FROM cs.skins) AS skins,
|
||||
(SELECT count(*)::int FROM cs.items) AS configs,
|
||||
(SELECT max(day)::text FROM cs.daily_prices) AS latest_day,
|
||||
(SELECT count(*)::int FROM cs.daily_prices
|
||||
WHERE day = (SELECT max(day) FROM cs.daily_prices)) AS latest_rows,
|
||||
(SELECT count(DISTINCT item_id)::int FROM cs.daily_prices
|
||||
WHERE day = (SELECT max(day) FROM cs.daily_prices)) AS latest_configs,
|
||||
(SELECT greatest(reltuples::bigint, 0) FROM pg_class
|
||||
WHERE oid = 'cs.daily_prices'::regclass)::bigint AS rows,
|
||||
(SELECT min(day)::text FROM cs.daily_prices) AS earliest_day,
|
||||
(SELECT max(last_fetched_at) FROM cs.price_streams) AS fetched_at`)) as unknown as {
|
||||
skins: number;
|
||||
configs: number;
|
||||
latest_day: string | null;
|
||||
latest_rows: number;
|
||||
latest_configs: number;
|
||||
rows: string;
|
||||
earliest_day: string | null;
|
||||
fetched_at: Date | null;
|
||||
}[];
|
||||
return row;
|
||||
}
|
||||
|
||||
export type SkinHit = {
|
||||
slug: string;
|
||||
name: string;
|
||||
kind: string;
|
||||
image: string | null;
|
||||
rarity: string | null;
|
||||
rarity_color: string | null;
|
||||
configs: number;
|
||||
from_cents: number | null;
|
||||
listings: number | null;
|
||||
};
|
||||
|
||||
/** Skins matching every word of `q`, with today's cheapest EUR listing across their configs. */
|
||||
export async function searchSkins(q: string, kind: string, sort: string, limit = 60, offset = 0) {
|
||||
const words = q
|
||||
.trim()
|
||||
.slice(0, 100)
|
||||
.split(/\s+/)
|
||||
.filter(Boolean)
|
||||
.slice(0, 6)
|
||||
.map(
|
||||
(word) => `%${word.replaceAll('\\', '\\\\').replaceAll('%', '\\%').replaceAll('_', '\\_')}%`
|
||||
);
|
||||
const filter = words.length
|
||||
? sql.join(
|
||||
words.map((word) => sql`s.name ILIKE ${word} ESCAPE '\\'`),
|
||||
sql` AND `
|
||||
)
|
||||
: sql`true`;
|
||||
const kindFilter =
|
||||
kind && kinds.some(([value]) => value === kind) ? sql`s.kind = ${kind}` : sql`true`;
|
||||
const order =
|
||||
sort === 'price'
|
||||
? sql`p.from_cents DESC NULLS LAST, s.name`
|
||||
: sort === 'name'
|
||||
? sql`s.name`
|
||||
: sql`p.listings DESC NULLS LAST, s.name`;
|
||||
const rows = await db.execute(sql`
|
||||
WITH listing AS (
|
||||
SELECT id FROM cs.price_streams WHERE source = 'skinport' AND kind = 'lowest-listing'
|
||||
), latest AS (
|
||||
SELECT max(day) AS day FROM cs.daily_prices WHERE stream_id = (SELECT id FROM listing)
|
||||
), p AS (
|
||||
SELECT i.skin_id, min(dp.price_cents)::int AS from_cents, sum(dp.volume)::int AS listings
|
||||
FROM cs.daily_prices dp JOIN cs.items i ON i.id = dp.item_id
|
||||
WHERE dp.stream_id = (SELECT id FROM listing) AND dp.day = (SELECT day FROM latest)
|
||||
GROUP BY i.skin_id
|
||||
)
|
||||
SELECT s.slug, s.name, s.kind, s.image, s.rarity, s.rarity_color, p.from_cents, p.listings,
|
||||
(SELECT count(*)::int FROM cs.items i WHERE i.skin_id = s.id) AS configs
|
||||
FROM cs.skins s LEFT JOIN p ON p.skin_id = s.id
|
||||
WHERE ${filter} AND ${kindFilter}
|
||||
ORDER BY ${words.length ? sql`(s.name ILIKE ${words[0].slice(1)} ESCAPE '\\') DESC,` : sql``} ${order}
|
||||
LIMIT ${Math.min(120, Math.max(1, limit))} OFFSET ${Math.min(50_000, Math.max(0, offset))}`);
|
||||
return rows as unknown as SkinHit[];
|
||||
}
|
||||
|
||||
export type ConfigRow = {
|
||||
id: number;
|
||||
market_hash_name: string;
|
||||
phase: string | null;
|
||||
wear: string | null;
|
||||
stattrak: boolean;
|
||||
souvenir: boolean;
|
||||
icon_url: string | null;
|
||||
prices: {
|
||||
stream: number;
|
||||
cents: number;
|
||||
eur_cents: number;
|
||||
volume: number | null;
|
||||
day: string;
|
||||
}[];
|
||||
};
|
||||
|
||||
export type Variant = 'normal' | 'stattrak' | 'souvenir';
|
||||
export const variantOf = (row: { stattrak: boolean; souvenir: boolean }): Variant =>
|
||||
row.souvenir ? 'souvenir' : row.stattrak ? 'stattrak' : 'normal';
|
||||
const shortToWear = Object.fromEntries(Object.entries(wearShort).map(([wear, s]) => [s, wear]));
|
||||
|
||||
export async function loadSkin(slug: string) {
|
||||
const [skin] = (await db.execute(sql`SELECT id, slug, name, kind, weapon, pattern, category,
|
||||
rarity, rarity_color, image, min_float, max_float, collections
|
||||
FROM cs.skins WHERE slug = ${slug}`)) as unknown as {
|
||||
id: string;
|
||||
slug: string;
|
||||
name: string;
|
||||
kind: string;
|
||||
weapon: string | null;
|
||||
pattern: string | null;
|
||||
category: string | null;
|
||||
rarity: string | null;
|
||||
rarity_color: string | null;
|
||||
image: string | null;
|
||||
min_float: number | null;
|
||||
max_float: number | null;
|
||||
collections: string[] | null;
|
||||
}[];
|
||||
if (!skin) return null;
|
||||
// Latest price per config and stream within the last 10 days, converted to EUR.
|
||||
const configs = (await db.execute(sql`
|
||||
WITH fx AS (SELECT usd_eur FROM cs.fx_rates ORDER BY day DESC LIMIT 1)
|
||||
SELECT i.id, i.market_hash_name, i.phase, i.wear, i.stattrak, i.souvenir, i.icon_url,
|
||||
coalesce((SELECT json_agg(json_build_object('stream', l.stream_id, 'cents', l.price_cents,
|
||||
'eur_cents', CASE WHEN st.currency = 'USD'
|
||||
THEN round(l.price_cents * coalesce((SELECT usd_eur FROM fx), 0.92))::int
|
||||
ELSE l.price_cents END,
|
||||
'volume', l.volume, 'day', l.day::text) ORDER BY l.stream_id)
|
||||
FROM (SELECT DISTINCT ON (dp.stream_id) dp.stream_id, dp.price_cents, dp.volume, dp.day
|
||||
FROM cs.daily_prices dp WHERE dp.item_id = i.id AND dp.day >= current_date - 10
|
||||
ORDER BY dp.stream_id, dp.day DESC) l
|
||||
JOIN cs.price_streams st ON st.id = l.stream_id), '[]'::json) AS prices
|
||||
FROM cs.items i WHERE i.skin_id = ${skin.id}`)) as unknown as ConfigRow[];
|
||||
configs.sort((a, b) => configRank(a) - configRank(b));
|
||||
return { skin, configs };
|
||||
}
|
||||
|
||||
/** Pick the config from ?v=&wear=&phase=, falling back to the cheapest priced normal config. */
|
||||
export function pickConfig(configs: ConfigRow[], params: URLSearchParams) {
|
||||
const variant = params.get('v') as Variant | null;
|
||||
const wear = shortToWear[params.get('wear') ?? ''] ?? null;
|
||||
const phase = params.get('phase') || null;
|
||||
// Default to the most traded normal config (most listings/sales across sources).
|
||||
const liquidity = (row: ConfigRow) => row.prices.reduce((sum, p) => sum + (p.volume ?? 0), 0);
|
||||
const fallback = () =>
|
||||
configs
|
||||
.filter((row) => row.prices.length && !row.phase && variantOf(row) === 'normal')
|
||||
.sort((a, b) => liquidity(b) - liquidity(a))[0] ??
|
||||
configs.find((row) => row.prices.length) ??
|
||||
configs[0] ??
|
||||
null;
|
||||
if (!variant && !params.has('wear') && !params.has('phase')) return fallback();
|
||||
const exact = configs.find(
|
||||
(row) =>
|
||||
(!variant || variantOf(row) === variant) &&
|
||||
(params.has('wear') ? row.wear === wear : true) &&
|
||||
(params.has('phase') ? row.phase === phase : !row.phase)
|
||||
);
|
||||
if (exact) return exact;
|
||||
const near = configs.find(
|
||||
(row) => (!variant || variantOf(row) === variant) && (!wear || row.wear === wear)
|
||||
);
|
||||
return near ?? fallback();
|
||||
}
|
||||
|
||||
export type SeriesPoint = [string, number];
|
||||
|
||||
/** Daily EUR series per stream for one config. Doppler phases also get the phase-blind
|
||||
* listing's streams they lack (e.g. Steam has no phases), labelled as "any phase". */
|
||||
export async function loadSeries(config: ConfigRow, from: string | null) {
|
||||
const ids = [config.id];
|
||||
if (config.phase) {
|
||||
const [base] = (await db.execute(sql`SELECT id FROM cs.items
|
||||
WHERE market_hash_name = ${config.market_hash_name} AND phase IS NULL`)) as unknown as {
|
||||
id: number;
|
||||
}[];
|
||||
if (base) ids.push(base.id);
|
||||
}
|
||||
const rows = (await db.execute(sql`
|
||||
SELECT dp.item_id, dp.stream_id, dp.day::text AS day, dp.volume,
|
||||
CASE WHEN st.currency = 'USD' THEN round(dp.price_cents * coalesce(
|
||||
(SELECT usd_eur FROM cs.fx_rates f WHERE f.day <= dp.day ORDER BY f.day DESC LIMIT 1),
|
||||
(SELECT usd_eur FROM cs.fx_rates ORDER BY day LIMIT 1), 0.92))::int
|
||||
ELSE dp.price_cents END AS eur_cents
|
||||
FROM cs.daily_prices dp JOIN cs.price_streams st ON st.id = dp.stream_id
|
||||
WHERE dp.item_id IN (${sql.join(
|
||||
ids.map((id) => sql`${id}`),
|
||||
sql`,`
|
||||
)}) ${from ? sql`AND dp.day >= ${from}::date` : sql``}
|
||||
ORDER BY dp.day`)) as unknown as {
|
||||
item_id: number;
|
||||
stream_id: number;
|
||||
day: string;
|
||||
volume: number | null;
|
||||
eur_cents: number;
|
||||
}[];
|
||||
const own = new Set(rows.filter((r) => r.item_id === config.id).map((r) => r.stream_id));
|
||||
const series = new Map<string, { stream: number; anyPhase: boolean; points: SeriesPoint[] }>();
|
||||
for (const row of rows) {
|
||||
const anyPhase = row.item_id !== config.id;
|
||||
if (anyPhase && own.has(row.stream_id)) continue;
|
||||
const key = `${row.stream_id}:${anyPhase}`;
|
||||
const entry = series.get(key) ?? { stream: Number(row.stream_id), anyPhase, points: [] };
|
||||
entry.points.push([row.day, row.eur_cents]);
|
||||
series.set(key, entry);
|
||||
}
|
||||
const windows = (await db.execute(sql`SELECT item_id, source, currency, span, median_cents,
|
||||
avg_cents, min_cents, max_cents, volume FROM cs.price_windows
|
||||
WHERE item_id IN (${sql.join(
|
||||
ids.map((id) => sql`${id}`),
|
||||
sql`,`
|
||||
)})`)) as unknown as {
|
||||
item_id: number;
|
||||
source: string;
|
||||
currency: string;
|
||||
span: string;
|
||||
median_cents: number | null;
|
||||
avg_cents: number | null;
|
||||
min_cents: number | null;
|
||||
max_cents: number | null;
|
||||
volume: number | null;
|
||||
}[];
|
||||
const [fx] = (await db.execute(
|
||||
sql`SELECT usd_eur::float AS rate, day::text FROM cs.fx_rates ORDER BY day DESC LIMIT 1`
|
||||
)) as unknown as { rate: number; day: string }[];
|
||||
return {
|
||||
series: [...series.values()],
|
||||
windows: windows
|
||||
.filter(
|
||||
(w) =>
|
||||
w.item_id === config.id ||
|
||||
!windows.some((o) => o.item_id === config.id && o.source === w.source)
|
||||
)
|
||||
.map((w) => ({ ...w, anyPhase: w.item_id !== config.id })),
|
||||
fx: fx ?? null
|
||||
};
|
||||
}
|
||||
|
||||
export { wearOrder, wearShort };
|
||||
@@ -5,11 +5,45 @@ import {
|
||||
text,
|
||||
timestamp,
|
||||
uniqueIndex,
|
||||
bigint
|
||||
bigint,
|
||||
boolean,
|
||||
date,
|
||||
real,
|
||||
smallint,
|
||||
numeric
|
||||
} from 'drizzle-orm/pg-core';
|
||||
import { sql } from 'drizzle-orm';
|
||||
import { csSchema } from './schemas';
|
||||
import { id } from './helpers';
|
||||
|
||||
// One finish or item, grouping all of its market configs (wear, StatTrak, Souvenir, phase).
|
||||
// Ids come from ByMykel/CSGO-API (skin_id / item id); items only seen in price feeds get `mkt-<slug>`.
|
||||
export const csSkins = csSchema.table(
|
||||
'skins',
|
||||
{
|
||||
id: text('id').primaryKey(),
|
||||
slug: text('slug').notNull(),
|
||||
name: text('name').notNull(),
|
||||
kind: text('kind').notNull(),
|
||||
weapon: text('weapon'),
|
||||
pattern: text('pattern'),
|
||||
category: text('category'),
|
||||
rarity: text('rarity'),
|
||||
rarityColor: text('rarity_color'),
|
||||
image: text('image'),
|
||||
minFloat: real('min_float'),
|
||||
maxFloat: real('max_float'),
|
||||
collections: text('collections').array(),
|
||||
source: text('source').notNull().default('bymykel'),
|
||||
updatedAt: timestamp('updated_at', { withTimezone: true }).notNull().defaultNow()
|
||||
},
|
||||
(table) => [
|
||||
uniqueIndex('skins_slug_idx').on(table.slug),
|
||||
index('skins_name_idx').on(table.name),
|
||||
index('skins_kind_idx').on(table.kind)
|
||||
]
|
||||
);
|
||||
|
||||
// A Steam market hash name identifies a listing, including wear and special variants.
|
||||
export const csMarketItems = csSchema.table(
|
||||
'items',
|
||||
@@ -19,12 +53,20 @@ export const csMarketItems = csSchema.table(
|
||||
name: text('name').notNull(),
|
||||
iconUrl: text('icon_url'),
|
||||
itemType: text('item_type'),
|
||||
// Catalog link and config facets. Doppler phases share a market hash name, so a phase
|
||||
// row is its own config next to the phase-less listing.
|
||||
skinId: text('skin_id').references(() => csSkins.id, { onDelete: 'set null' }),
|
||||
phase: text('phase'),
|
||||
wear: text('wear'),
|
||||
stattrak: boolean('stattrak').notNull().default(false),
|
||||
souvenir: boolean('souvenir').notNull().default(false),
|
||||
firstSeenAt: timestamp('first_seen_at', { withTimezone: true }).notNull().defaultNow(),
|
||||
lastSeenAt: timestamp('last_seen_at', { withTimezone: true }).notNull().defaultNow()
|
||||
},
|
||||
(table) => [
|
||||
uniqueIndex('items_hash_idx').on(table.marketHashName),
|
||||
index('items_name_idx').on(table.name)
|
||||
uniqueIndex('items_config_idx').on(table.marketHashName, sql`coalesce(${table.phase}, '')`),
|
||||
index('items_name_idx').on(table.name),
|
||||
index('items_skin_idx').on(table.skinId)
|
||||
]
|
||||
);
|
||||
|
||||
@@ -82,9 +124,64 @@ export const csPriceStreams = csSchema.table(
|
||||
{
|
||||
source: text('source').notNull(),
|
||||
currency: text('currency').notNull(),
|
||||
kind: text('kind').notNull()
|
||||
kind: text('kind').notNull(),
|
||||
id: smallint('id').generatedByDefaultAsIdentity(),
|
||||
label: text('label'),
|
||||
lastFetchedAt: timestamp('last_fetched_at', { withTimezone: true }),
|
||||
lastRows: integer('last_rows'),
|
||||
lastError: text('last_error')
|
||||
},
|
||||
(table) => [
|
||||
primaryKey({ name: 'price_streams_pkey', columns: [table.source, table.currency, table.kind] })
|
||||
primaryKey({ name: 'price_streams_pkey', columns: [table.source, table.currency, table.kind] }),
|
||||
uniqueIndex('price_streams_id_idx').on(table.id)
|
||||
]
|
||||
);
|
||||
|
||||
// One price per config per stream per UTC day (idempotent upsert). Prices stay in the stream's
|
||||
// own currency; fx_rates converts USD streams to EUR for display.
|
||||
export const csDailyPrices = csSchema.table(
|
||||
'daily_prices',
|
||||
{
|
||||
itemId: integer('item_id')
|
||||
.notNull()
|
||||
.references(() => csMarketItems.id, { onDelete: 'cascade' }),
|
||||
streamId: smallint('stream_id').notNull(),
|
||||
day: date('day').notNull(),
|
||||
priceCents: integer('price_cents').notNull(),
|
||||
volume: integer('volume')
|
||||
},
|
||||
(table) => [
|
||||
primaryKey({ name: 'daily_prices_pkey', columns: [table.itemId, table.streamId, table.day] }),
|
||||
index('daily_prices_day_idx').on(table.day, table.streamId)
|
||||
]
|
||||
);
|
||||
|
||||
// Rolling sale aggregates (24h/7d/30d/90d) as reported by the source, latest snapshot only.
|
||||
export const csPriceWindows = csSchema.table(
|
||||
'price_windows',
|
||||
{
|
||||
itemId: integer('item_id')
|
||||
.notNull()
|
||||
.references(() => csMarketItems.id, { onDelete: 'cascade' }),
|
||||
source: text('source').notNull(),
|
||||
currency: text('currency').notNull(),
|
||||
span: text('span').notNull(),
|
||||
medianCents: integer('median_cents'),
|
||||
avgCents: integer('avg_cents'),
|
||||
minCents: integer('min_cents'),
|
||||
maxCents: integer('max_cents'),
|
||||
volume: integer('volume'),
|
||||
updatedAt: timestamp('updated_at', { withTimezone: true }).notNull().defaultNow()
|
||||
},
|
||||
(table) => [
|
||||
primaryKey({
|
||||
name: 'price_windows_pkey',
|
||||
columns: [table.itemId, table.source, table.span]
|
||||
})
|
||||
]
|
||||
);
|
||||
|
||||
export const csFxRates = csSchema.table('fx_rates', {
|
||||
day: date('day').primaryKey(),
|
||||
usdEur: numeric('usd_eur', { precision: 12, scale: 8 }).notNull()
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user