HuaRenCa
Back to Forum
Community

Asistente mejorado de CardCenter (script de usuarios)

美辰
美辰

1 week ago

Esta herramienta es el resultado de la modificación de dos pequeños scripts de usuarios: CardCenter / Aligned Incentives, que ocultan automáticamente el margen/beneficio negativo.

Se aplica a las páginas Deals y Rates de CardCenter. Funciones principales:

Filtro de Margin personalizado: introduce el umbral mínimo en el encabezado, haz clic en «Aplicar» o pulsa Enter para conservar las ofertas con un Margin mayor o igual a ese valor; la configuración se guarda automáticamente.

Ordenación al hacer clic en el encabezado: las flechas junto al nombre de la columna permiten alternar entre orden descendente, ascendente y el orden original.

Conservación de grupos: las ofertas se agrupan por marca o Deal y se ordenan de forma sincronizada dentro de cada grupo; si ninguna oferta del grupo cumple el umbral, se oculta el título del grupo.

Restauración de la ordenación con un clic: haz clic en ↺ para recuperar el orden original manteniendo el filtro actual.

Actualización automática: cuando cambia el contenido de la página, se vuelve a filtrar y ordenar automáticamente.

Al ordenar, los grupos se ordenan según el valor máximo o mínimo de las ofertas que cumplen el filtro. Las ofertas con Margin vacío se ocultan.

El script solo modifica la visualización local de la página; no envía, reserva ni realiza pedidos automáticamente.

El resultado es el siguiente:

// ==UserScript== // @name CardCenter - Deals Margin Filter // @namespace cardcenter-deals-filter // @version 2.3 // @description Margin filter and column sorting for Deals and Rates. // @match https://cardcenter.cc/Deals* // @match https://www.cardcenter.cc/Deals* // @match https://cardcenter.cc/Rates* // @match https://www.cardcenter.cc/Rates* // @run-at document-idle // @grant none // ==/UserScript==

(() => { 'use strict';

const DEFAULT_MIN_MARGIN = -4; const STORAGE_KEY = 'tm-cardcenter-min-margin'; const PANEL_ID = 'tm-cardcenter-margin-panel'; const HIDDEN_CLASS = 'tm-cardcenter-margin-hidden'; const SORT_CLASS = 'tm-cc-sort';

if (document.getElementById(PANEL_ID)) return;

let minMargin = DEFAULT_MIN_MARGIN;

try { const saved = localStorage.getItem(STORAGE_KEY);

if ( saved !== null && saved.trim() && Number.isFinite(Number(saved)) ) { minMargin = Number(saved); } } catch (error) { console.warn('[CardCenter Filter]', error); }

const style = document.createElement('style');

style.textContent = ` .${HIDDEN_CLASS} { display: none !important; }

/* Mantiene el nombre de la columna y la flecha de ordenación en la misma línea y con alineación vertical uniforme. */ table > thead > tr > th { white-space: nowrap !important; vertical-align: middle !important; }

.${SORT_CLASS} { display: inline-flex !important; align-items: center; justify-content: center; vertical-align: middle !important; box-sizing: border-box; width: 22px; height: 24px; margin-left: 5px; padding: 0; border: 1px solid #788390; border-radius: 4px; background: transparent; color: inherit; font: inherit; font-size: 12px; line-height: 1 !important; cursor: pointer; }

.${SORT_CLASS}[data-active="true"] { background: #2563eb; border-color: #2563eb; color: #fff; }

/* La flecha se muestra mediante CSS y no entra en el textContent del encabezado. */ .${SORT_CLASS}::after { content: attr(data-symbol); }

.tm-cc-margin-heading { white-space: nowrap; }

#${PANEL_ID} { display: inline-flex; position: static; vertical-align: middle; align-items: center; gap: 4px; margin-left: 8px; padding: 0; border: 0; background: transparent; color: inherit; font: 12px/1.5 Arial, sans-serif; font-weight: normal; white-space: nowrap; }

#${PANEL_ID} input { width: 64px; min-width: 0; box-sizing: border-box; height: 26px; padding: 2px 4px; border: 1px solid #87919c; border-radius: 4px; background: transparent; color: inherit; font: inherit; }

#${PANEL_ID} button { height: 26px; padding: 2px 6px; border: 0; border-radius: 4px; background: #2563eb; color: #fff; font: inherit; cursor: pointer; }

#${PANEL_ID} .tm-reset { background: #495057; }

#${PANEL_ID} button::after, #${PANEL_ID} .tm-ui-label::after { content: attr(data-ui); }

.tm-cc-announcement { position: absolute; width: 1px; height: 1px; padding: 0; overflow: hidden; clip-path: inset(50%); white-space: nowrap; } `;

document.head.appendChild(style);

const panel = document.createElement('span');

panel.id = PANEL_ID; panel.setAttribute('role', 'group'); panel.setAttribute('aria-label', 'Filtro de Margin mínimo y ordenación');

// El texto dentro del encabezado se muestra mediante CSS para no contaminar el data-label del sitio. panel.innerHTML = ` <span class="tm-ui-label" data-ui="≥" aria-hidden="true"

</span>

<input id="tm-cardcenter-margin-input" type="number" step="any" required aria-label="Porcentaje de Margin mínimo" title="Margin mínimo, incluido el igual; pulsa Enter para aplicar"

<span class="tm-ui-label" data-ui="%" aria-hidden="true"

</span>

<button type="button" class="tm-apply" data-ui="Aplicar" aria-label="Aplicar filtro de Margin" title="Aplicar Margin mínimo"

</button>

<button type="button" class="tm-reset" data-ui="↺" aria-label="Restaurar orden original" title="Restaurar orden original"

</button>

`;

const input = panel.querySelector('input');

const status = document.createElement('span'); status.className = 'tm-cc-announcement'; status.setAttribute('aria-live', 'polite'); document.body.appendChild(status);

panel.addEventListener('click', event => { event.stopPropagation(); });

input.value = String(minMargin);

const states = new WeakMap(); const order = new WeakMap();

let nextOrder = 0;

function originalOrder(node) { if (!node) return Number.MAX_SAFE_INTEGER;

if (!order.has(node)) { order.set(node, nextOrder++); }

return order.get(node); }

// Compatibilidad con versiones antiguas en las que el sitio copiaba la flecha en data-label. const normalize = text => text .replace(/[↕↑↓⇅▲▼]/g, '') .replace(/\s+/g, ' ') .trim() .toLowerCase();

const normalizeSigns = text => text .replace(/\u00a0/g, ' ') .replace(/[−–﹣-]/g, '-') .trim();

function parsePercent(text) { const match = normalizeSigns(text).match( /(()?\s*([+-]?)\s*(\d+(?:,\d{3})(?:.\d+)?|.\d+)\s%\s*())?/ );

if (!match) return null;

const value = Number(match[3].replace(/,/g, ''));

const negative = match[2] === '-' || Boolean(match[1] && match[4]);

return negative ? -value : value; }

function columnKey(th) { const clone = th.cloneNode(true);

clone .querySelectorAll('.' + SORT_CLASS + ', #' + PANEL_ID) .forEach(element => element.remove());

return normalize(clone.textContent); }

function cellFor(row, key, columns) { const cells = Array.from(row.cells);

const labelled = cells.find(cell => normalize(cell.getAttribute('data-label') || '') === key );

if (labelled) return labelled;

// Si ya hay data-label, no se adivinan las columnas faltantes por índice. if (cells.some(cell => cell.hasAttribute('data-label'))) { return null; }

return row.cells[columns.indexOf(key)] || null; }

function valueFor(row, key, columns) { const text = normalizeSigns( cellFor(row, key, columns)?.textContent || '' );

if (!text) return null;

if (['margin', 'you pay', 'we pay'].includes(key)) { return parsePercent(text); }

if (['brand', 'deal'].includes(key)) { return normalize(text); }

if ( key === 'available cap' && /^(none left|expired)$/i.test(text) ) { return null; }

if (key === 'submission deadline') { const relative = text.match( /^(\d+(?:.\d+)?)\s*(hours?|days?|weeks?)\s+after\s+approval/i );

if (!relative) return null;

const factor = /^hour/i.test(relative[2]) ? 1 / 24 : /^week/i.test(relative[2]) ? 7 : 1;

return Number(relative[1]) * factor; }

// Para el rango de denominación se toma el límite inferior; para el cupo, el total antes del paréntesis. const match = text.match( /^[^\d+-]([+-]?(?:\d[\d,](?:.\d+)?|.\d+))\s*([kKmM])?/ );

if (!match) return null;

const multiplier = match[2] ? match[2].toLowerCase() === 'k' ? 1000 : 1000000 : 1;

return Number(match[1].replace(/,/g, '')) * multiplier; }

function compareValues(a, b, direction) { if (a === null && b === null) return 0; if (a === null) return 1; if (b === null) return -1;

const comparison = typeof a === 'string' ? a.localeCompare(b, undefined, { numeric: true, sensitivity: 'base' }) : a - b;

return comparison * direction; }

function isHeader(row) { return Array.from(row.cells).some(cell => cell.colSpan > 1 ); }

function groupsFor(table) { const groups = []; const bodies = Array.from(table.tBodies);

const splitBodies = bodies.some(body => body.classList.contains('table-stacked-child') );

if (splitBodies) { // Rates: el título de la marca y cada oferta están en tbody independientes. let group = null;

for (const body of bodies) { originalOrder(body);

if (!body.classList.contains('table-stacked-child')) { group = { node: body, header: body.rows[0], entries: [], split: true };

groups.push(group); } else { if (!group) { group = { node: null, header: null, entries: [], split: true };

groups.push(group); }

if (body.rows[0]) { group.entries.push({ node: body, row: body.rows[0] }); } } } } else { // Deals: un tbody contiene la fila de título y las filas de ofertas. for (const body of bodies) { originalOrder(body);

const rows = Array.from(body.rows); const header = rows.find(isHeader) || null;

const entries = rows .filter(row => !isHeader(row) && !row.querySelector('th') ) .map(row => { originalOrder(row); return { node: row, row }; });

groups.push({ node: body, header, entries, split: false }); } }

return groups; }

function reorder(parent, desired) { const selected = new Set(desired);

const current = Array.from(parent.children).filter(node => selected.has(node) );

if ( !current.length || current.every((node, index) => node === desired[index]) ) { return; }

const anchor = current[current.length - 1].nextSibling;

desired.forEach(node => { parent.insertBefore(node, anchor); }); }

function prepareTable(table) { const header = table.querySelector('thead tr'); if (!header) return null;

const columns = Array.from(header.cells).map(columnKey); if (!columns.includes('margin')) return null;

if (!states.has(table)) { states.set(table, { key: null, direction: -1 }); }

const state = states.get(table);

Array.from(header.cells).forEach((th, index) => { const key = columns[index]; if (!key) return;

let button = th.querySelector('.' + SORT_CLASS);

if (!button) { button = document.createElement('button'); button.type = 'button'; button.className = SORT_CLASS;

button.addEventListener('click', event => { event.preventDefault(); event.stopPropagation();

if (state.key !== key) { state.key = key; state.direction = -1; } else if (state.direction === -1) { state.direction = 1; } else { state.key = null; }

refresh(); });

th.appendChild(button); }

const active = state.key === key;

// Se mantiene vacío el textContent del botón; la flecha se muestra mediante CSS. if (button.textContent) { button.textContent = ''; }

button.dataset.symbol = active ? state.direction === -1 ? '↓' : '↑' : '↕';

button.dataset.active = String(active); button.title = key + ': haz clic para alternar descendente / ascendente / orden original'; button.setAttribute('aria-label', 'Ordenar por ' + key);

th.setAttribute( 'aria-sort', active ? state.direction === -1 ? 'descending' : 'ascending' : 'none' );

// Coloca el control de Margin mínimo junto al nombre de la columna. if (key === 'margin') { th.classList.add('tm-cc-margin-heading');

if (panel.parentElement !== th) { th.appendChild(panel); } } });

return { columns, state }; }

function processTable(table, columns, state) { const groups = groupsFor(table);

let total = 0; let shown = 0;

for (const group of groups) { let anyVisible = false;

for (const entry of group.entries) { total++;

const margin = parsePercent( cellFor(entry.row, 'margin', columns)?.textContent || '' );

entry.visible = margin !== null && margin >= minMargin;

entry.node.classList.toggle( HIDDEN_CLASS, !entry.visible );

if (entry.visible) { shown++; anyVisible = true; } }

if (group.header) { group.header.classList.toggle( HIDDEN_CLASS, !anyVisible ); }

if (group.node) { group.node.classList.toggle( HIDDEN_CLASS, !anyVisible ); }

group.entries.sort((a, b) => { if (!state.key) { return originalOrder(a.node) - originalOrder(b.node); }

return compareValues( valueFor(a.row, state.key, columns), valueFor(b.row, state.key, columns), state.direction ) || originalOrder(a.node) - originalOrder(b.node); });

if (!group.split && group.node) { reorder( group.node, group.entries.map(entry => entry.node) ); }

const candidates = group.entries .filter(entry => entry.visible) .map(entry => valueFor(entry.row, state.key, columns) ) .filter(value => value !== null);

candidates.sort((a, b) => compareValues(a, b, state.direction) );

group.score = candidates.length ? candidates[0] : null; }

groups.sort((a, b) => { const ordinal = originalOrder(a.node || a.entries[0]?.node) - originalOrder(b.node || b.entries[0]?.node);

return state.key ? compareValues(a.score, b.score, state.direction) || ordinal : ordinal; });

const desired = groups.flatMap(group => group.split ? [ ...(group.node ? [group.node] : []), ...group.entries.map(entry => entry.node) ] : [group.node] );

reorder(table, desired);

return { total, shown }; }

let timer;

const observer = new MutationObserver(mutations => { if ( mutations.every(mutation => panel.contains(mutation.target) ) ) { return; }

clearTimeout(timer); timer = setTimeout(refresh, 100); });

function refresh() { clearTimeout(timer);

// Se pausa la observación durante la ordenación para evitar bucles provocados por el propio script. observer.disconnect();

let total = 0; let shown = 0;

try { for (const table of document.querySelectorAll('table')) { const meta = prepareTable(table); if (!meta) continue;

const counts = processTable( table, meta.columns, meta.state );

total += counts.total; shown += counts.shown; }

status.textContent = Margin ≥ ${minMargin}% · Mostrando ${shown} / ${total};

panel.title = status.textContent; } catch (error) { status.textContent = 'Error de procesamiento; consulta la consola.'; panel.title = status.textContent; console.error('[CardCenter Filter]', error); } finally { observer.observe(document.body, { childList: true, subtree: true, characterData: true, attributes: true, attributeFilter: ['data-label'] }); } }

function applySettings() { if ( !input.reportValidity() || !Number.isFinite(input.valueAsNumber) ) { return; }

minMargin = input.valueAsNumber;

try { localStorage.setItem(STORAGE_KEY, String(minMargin)); } catch (error) { console.warn('[CardCenter Filter]', error); }

refresh(); }

panel .querySelector('.tm-apply') .addEventListener('click', applySettings);

input.addEventListener('keydown', event => { if (event.key === 'Enter') { event.preventDefault(); applySettings(); } });

panel .querySelector('.tm-reset') .addEventListener('click', () => { document.querySelectorAll('table').forEach(table => { const state = states.get(table);

if (state) { state.key = null; } });

refresh(); });

refresh(); })();

Asistente mejorado de CardCenter (script de usuarios)

5
1.7K

Comments (5)

Your avatar
Sign in to comment
任城东
任城东1 week ago

Desde el punto de vista del mantenimiento, conviene empezar añadiendo al script un bloque de comentarios con el número de versión y el registro de cambios, y luego plantearse convertir el umbral de filtrado en varios valores predefinidos. Así, cuando más adelante modifiques el código o cambies de dispositivo, podrás confirmar rápidamente qué versión se está ejecutando.

nihao997847
nihao9978471 week ago

No todos los navegadores ni gestores de userscripts admiten localStorage y @match exactamente igual, así que antes de cambiar de entorno conviene probarlo primero a pequeña escala.

深圳门窗人
深圳门窗人1 week ago

Antes de nada, quiero confirmar una cosa: el script localiza las columnas por el texto del encabezado y el data-label. Si una actualización de CardCenter cambia los nombres de las columnas por abreviaturas, o si en la misma tabla aparecen dos columnas Margin con el mismo nombre, ¿cómo gestionarían columnKey y cellFor esa situación? ¿Podría ocurrir que no se obtuviera ningún valor para toda una columna y que el filtrado dejara de funcionar directamente?

不废话
不废话1 week ago

Sobre lo de la actualización automática, tengo mis reservas. Si el contenido de la página cambia y se vuelve a filtrar y ordenar, y si CardCenter también se actualiza dinámicamente, los reordenamientos frecuentes podrían hacer que la fila que estás viendo salte de sitio, e incluso entrar en conflicto con el orden propio del sitio. Sugiero añadir una limitación de frecuencia o que solo se active cuando cambie el encabezado de la tabla.

优米
优米1 week ago

Ocultar directamente estos dos puntos con los valores predeterminados -4 y un margen vacío es bastante importante, ya que de forma predeterminada se está escondiendo una parte de la cotización.