← back to Selfadhesivewallpaper
server.js
275 lines
/**
* SELF-ADHESIVE WALLPAPER — DW family vertical
* Curated slice from live designerwallcoverings.com Shopify catalog.
*/
try { require('dotenv').config({ path: require('path').join(__dirname, '.env') }); } catch (e) {}
const express = require('express');
const path = require('path');
const fs = require('fs');
const PORT = process.env.PORT || 9873;
const DW_SHOPIFY = 'https://designerwallcoverings.com';
const __SITE = path.basename(__dirname);
// Admin catalog (PG-backed) is opt-in via MICROSITE_ADMIN_ENABLED=true. Prod
// stays static-only (data/products.json) so Kamatera doesn't need `pg` or the
// _shared/ tree. Dev (Mac2) flips the flag on to use dw_unified + /admin/catalog.
const ADMIN_ENABLED = process.env.MICROSITE_ADMIN_ENABLED === 'true';
let catalog = null;
if (ADMIN_ENABLED) {
try { catalog = require('../_shared/admin-catalog'); }
catch (e) { console.error(`[${__SITE}] admin-catalog unavailable (${e.message}) — falling back to static JSON`); }
}
const siteCfg = JSON.parse(fs.readFileSync(path.join(__dirname, 'site.config.json'), 'utf8'));
const SITE_SLUG = siteCfg.slug || __SITE;
const SITE_RAILS = Array.isArray(siteCfg.rails) ? siteCfg.rails : [];
function isJunk(p) {
if (!p.image_url || !p.image_url.trim()) return true;
if (!p.handle && !p.sku) return true;
const t = p.title || '';
if (/lamp|rug|pillow|throw|tripod|frame|mirror|vase|candle|sculpture|figurine/i.test(t)) return true;
if (/visual.{0,3}merchandiser/i.test(t)) return true;
if (/(?:^|\W)image[ _-]?4(?:\W|$)/i.test(t)) return true;
if (/bh.?90210|beverly.?hills.?90210|iconic.{0,4}bh/i.test(t)) return true;
return false;
}
// Catalog now lives in dw_unified.microsite_products — populated async at
// startup (see bottom of file). Falls back to data/products.json if PG is down.
let PRODUCTS = [];
let DROPPED = 0;
// graphics-loop pass 12: niche keyword filter — only show products that fit this site's niche
const NICHE_POS = ["peel","stick","removable","self-adhesive","renter","temporary"];
const NICHE_NEG = ["solid","blank","plain"];
function nicheFit(p) {
const blob = ((p.title || '') + ' ' + (p.tags || []).join(' ')).toLowerCase();
if (NICHE_NEG.some(n => blob.includes(n.toLowerCase()))) return false;
return NICHE_POS.length === 0 || NICHE_POS.some(k => blob.includes(k.toLowerCase()));
}
// Niche-filtered view of PRODUCTS — recomputed after the async catalog load.
let PRODUCTS_NICHE = [];
// DW STANDARD sort — honors the ?sort= param sent by the frontend select.
const COLOR_ORDER = ['white','cream','beige','tan','brown','gold','yellow','orange','red','pink','purple','blue','green','grey','gray','silver','black'];
function colorRank(p) {
const blob = ((p.title || '') + ' ' + (p.tags || []).join(' ')).toLowerCase();
for (let i = 0; i < COLOR_ORDER.length; i++) if (blob.includes(COLOR_ORDER[i])) return i;
return COLOR_ORDER.length;
}
function styleKey(p) {
const blob = ((p.aesthetic || '') + ' ' + (p.title || '') + ' ' + (p.tags || []).join(' ')).toLowerCase();
const STYLES = ['traditional','modern','floral','damask','geometric','abstract','botanical','chinoiserie','natural','striped'];
for (const s of STYLES) if (blob.includes(s)) return s;
return p.aesthetic || 'zzz';
}
function sortProducts(list, mode) {
if (mode === 'sku') return [...list].sort((a,b) => String(a.sku || a.handle || '').localeCompare(String(b.sku || b.handle || '')));
if (mode === 'title') return [...list].sort((a,b) => String(a.title || '').localeCompare(String(b.title || '')));
if (mode === 'color') return [...list].sort((a,b) => colorRank(a) - colorRank(b) || String(a.title || '').localeCompare(String(b.title || '')));
if (mode === 'style') return [...list].sort((a,b) => styleKey(a).localeCompare(styleKey(b)) || String(a.title || '').localeCompare(String(b.title || '')));
if (mode === 'price-asc') return [...list].sort((a,b) => (Number(a.price) || 0) - (Number(b.price) || 0));
if (mode === 'price-desc') return [...list].sort((a,b) => (Number(b.price) || 0) - (Number(a.price) || 0));
// List-view sortable columns — every column sortable in both directions.
if (mode === 'title-desc') return [...list].sort((a,b) => String(b.title || '').localeCompare(String(a.title || '')));
if (mode === 'sku-desc') return [...list].sort((a,b) => String(b.sku || b.handle || '').localeCompare(String(a.sku || a.handle || '')));
if (mode === 'vendor') return [...list].sort((a,b) => String(a.vendor || '').localeCompare(String(b.vendor || '')) || String(a.title || '').localeCompare(String(b.title || '')));
if (mode === 'vendor-desc') return [...list].sort((a,b) => String(b.vendor || '').localeCompare(String(a.vendor || '')) || String(a.title || '').localeCompare(String(b.title || '')));
if (mode === 'aesthetic') return [...list].sort((a,b) => String(a.aesthetic || '').localeCompare(String(b.aesthetic || '')) || String(a.title || '').localeCompare(String(b.title || '')));
if (mode === 'aesthetic-desc') return [...list].sort((a,b) => String(b.aesthetic || '').localeCompare(String(a.aesthetic || '')) || String(a.title || '').localeCompare(String(b.title || '')));
return list; // 'newest' = server's natural order
}
const app = express();
// Strip vendor names from all /api/* JSON responses (standing rule: DW vendor
// names NEVER in customer-facing UI). Must be mounted BEFORE route handlers.
app.use(require('../_shared/api-vendor-redact'));
app.use(express.json({ limit: "256kb" }));
// Site config — prefer _shared/site-config (canonical) but fall back to an
// inline minimal loader so this server.js is self-contained on Kamatera.
let cfg;
try {
cfg = require('../_shared/site-config').load(__dirname);
} catch (_) {
const domain = siteCfg.domain || `${SITE_SLUG}.com`;
cfg = Object.freeze({
slug: SITE_SLUG, siteName: siteCfg.siteName || SITE_SLUG,
domain, siteEmail: siteCfg.siteEmail || `info@${domain}`,
contact: { siteName: siteCfg.siteName || SITE_SLUG, domain,
siteEmail: siteCfg.siteEmail || `info@${domain}`,
zdColor: (siteCfg.theme && siteCfg.theme.accent) || '#C9A14B',
zdPosition: siteCfg.zdPosition || 'right' },
auth: { siteName: SITE_SLUG },
});
}
require("./_universal-contact")(app, cfg.contact);
require("./_universal-auth")(app, cfg.auth);
app.locals.siteConfig = cfg;
// Guard: never serve snapshot/backup files from the static root.
app.use((req, res, next) => {
if (/\.bak(\.[^/]*)?$/i.test(req.path) || /\.pre-[^/]*$/i.test(req.path)) {
return res.status(404).send('Not found');
}
next();
});
// Canonicalize legacy .html URLs → clean form with a 301 (static still serves
// both forms otherwise = duplicate content). Mounted BEFORE express.static.
const HTML_TO_CLEAN = { '/index.html': '/', '/history.html': '/history', '/care.html': '/care', '/trade.html': '/trade', '/sourcing.html': '/sourcing', '/vocabulary.html': '/vocabulary' };
app.get(/\.html$/i, (req, res, next) => {
const dest = HTML_TO_CLEAN[req.path];
if (dest) return res.redirect(301, dest);
next();
});
require('../_shared/_universal-promo-banner')(app, {}); // new-arrivals promo strip (Tier B)
app.use(express.static(path.join(__dirname, 'public')));
// Clean-URL routes for extension-less nav links.
const CLEAN_PAGES = { '/about': 'history.html', '/history': 'history.html', '/care': 'care.html', '/trade': 'trade.html', '/sourcing': 'sourcing.html', '/vocabulary': 'vocabulary.html' };
for (const [route, file] of Object.entries(CLEAN_PAGES)) {
app.get(route, (req, res, next) => {
const fp = path.join(__dirname, 'public', file);
fs.access(fp, fs.constants.R_OK, err => err ? next() : res.sendFile(fp));
});
}
// Shared filter — applied identically by /api/products and /api/facets so
// facet counts reflect the actual FILTERED result set, not the whole catalog.
// `skip` lets a facet dimension exclude its OWN filter for drill-down counts.
function filterProducts(opts, skip) {
const { q, aesthetic, vendor } = opts;
let list = PRODUCTS_NICHE;
if (q && skip !== 'q') {
const needle = String(q).toLowerCase();
list = list.filter(p => (p.title || '').toLowerCase().includes(needle) || (p.tags || []).some(t => t.toLowerCase().includes(needle)));
}
if (aesthetic && aesthetic !== 'all' && skip !== 'aesthetic') list = list.filter(p => p.aesthetic === aesthetic);
if (vendor && vendor !== 'all' && skip !== 'vendor') list = list.filter(p => p.vendor === vendor);
return list;
}
app.get('/api/products', (req, res) => {
const { q, aesthetic, vendor, sort = 'newest', page = 1, limit = 24 } = req.query;
let list = filterProducts({ q, aesthetic, vendor });
list = sortProducts(list, sort);
const total = list.length;
const pageNum = Math.max(1, parseInt(page));
const lim = Math.min(60, parseInt(limit));
const start = (pageNum - 1) * lim;
res.json({ total, page: pageNum, limit: lim, pages: Math.ceil(total / lim), items: list.slice(start, start + lim) });
});
app.get('/api/sliders', (req, res) => {
const out = [];
for (const a of SITE_RAILS) {
const items = PRODUCTS_NICHE.filter(p => p.aesthetic === a).slice(0, 12);
if (items.length >= 4) out.push({ aesthetic: a, items });
}
res.json({ rails: out });
});
app.get('/api/facets', (req, res) => {
const { q, aesthetic, vendor } = req.query;
const aesthetics = {}; const vendors = {};
// Each dimension's counts are computed over the set narrowed by the OTHER
// active facets (drill-down), so a chip shows how many results it WOULD yield.
for (const p of filterProducts({ q, aesthetic, vendor }, 'aesthetic')) {
aesthetics[p.aesthetic] = (aesthetics[p.aesthetic] || 0) + 1;
}
for (const p of filterProducts({ q, aesthetic, vendor }, 'vendor')) {
vendors[p.vendor] = (vendors[p.vendor] || 0) + 1;
}
// total = the fully-filtered result set (all active facets applied).
const total = filterProducts({ q, aesthetic, vendor }).length;
res.json({ aesthetics, vendors, total });
});
app.get('/api/health', (req, res) => res.json({ status: 'ok', count: PRODUCTS_NICHE.length, dropped: DROPPED }));
// Step 2 of the vendor handle/sku text-leak fix (2026-06-09): the client's
// /sample/ hrefs now point at the vendor-scrubbed `handle_display` slug
// (emitted by _shared/api-vendor-redact since Step 1), so the raw vendor-bearing
// handle never rides in the URL bar. This route is DUAL-KEY — it resolves the raw
// handle/sku FIRST (old bookmarks + buy path, byte-identical behavior), then falls
// back to a redacted->product map built after catalog load. If two raw handles
// redact to the same display slug, that slug is logged and left raw-only.
const { redactVendorText } = require('../_shared/vendor-text-redact');
let SAMPLE_DISPLAY = new Map(); // redacted display slug -> product
function buildSampleDisplayMap() {
const map = new Map();
const collided = new Set();
for (const p of PRODUCTS_NICHE) {
for (const key of [p.handle, p.sku]) {
if (!key) continue;
const d = redactVendorText(String(key));
if (!d || d === key) continue; // nothing redacted — raw route already matches
const prev = map.get(d);
if (prev && prev !== p) { collided.add(d); continue; }
map.set(d, p);
}
}
for (const d of collided) {
map.delete(d);
console.warn(`[selfadhesivewallpaper] /sample display-slug collision — keeping raw-only for "${d}"`);
}
SAMPLE_DISPLAY = map;
console.log(`[selfadhesivewallpaper] /sample dual-key map: ${map.size} display slugs, ${collided.size} collisions (raw-only)`);
}
app.get('/sample/:handle', (req, res) => {
const key = req.params.handle;
const p = PRODUCTS_NICHE.find(x => x.handle === key || x.sku === key) // raw first — old behavior intact
|| SAMPLE_DISPLAY.get(key); // then the redacted display form
if (!p) return res.status(404).send('Not found');
res.redirect(302, p.product_url || `${DW_SHOPIFY}/products/${encodeURIComponent(p.handle)}#sample`);
});
// sitemap.xml + robots.txt for SEO
app.get('/robots.txt', (req, res) => {
res.type('text/plain').send(`User-agent: *
Allow: /
Sitemap: https://selfadhesivewallpaper.com/sitemap.xml
`);
});
app.get('/sitemap.xml', (req, res) => {
const urls = ['/'];
const xml = `<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
${urls.map(u => ` <url><loc>https://selfadhesivewallpaper.com${u}</loc><changefreq>weekly</changefreq></url>`).join('\n')}
</urlset>`;
res.type('application/xml').send(xml);
});
// Admin catalog CRUD — /admin/catalog (basic-auth) + /api/admin/* REST.
if (catalog) catalog.mount(app, { siteSlug: SITE_SLUG, rails: SITE_RAILS });
// Load the catalog. When admin is enabled, prefer dw_unified; else static JSON.
(async () => {
let loaded = false;
if (catalog) {
try {
const rows = await catalog.getProducts(SITE_SLUG);
PRODUCTS = rows.filter(p => !isJunk(p));
DROPPED = rows.length - PRODUCTS.length;
console.log(`[${__SITE}] loaded ${rows.length} from dw_unified, kept ${PRODUCTS.length}, dropped ${DROPPED}`);
loaded = true;
} catch (e) {
console.error(`[${__SITE}] PG catalog load failed (${e.message}) — falling back to data/products.json`);
}
}
if (!loaded) {
try {
const raw = JSON.parse(fs.readFileSync(path.join(__dirname, 'data', 'products.json'), 'utf8'));
PRODUCTS = (Array.isArray(raw) ? raw : []).filter(p => !isJunk(p));
console.log(`[${__SITE}] loaded ${PRODUCTS.length} from data/products.json (static mode)`);
} catch (_) { PRODUCTS = []; }
}
PRODUCTS_NICHE = PRODUCTS.filter(nicheFit);
console.log(`[${__SITE}] niche filter: kept ${PRODUCTS_NICHE.length} of ${PRODUCTS.length}`);
buildSampleDisplayMap(); // Step 2: redacted->raw /sample resolver keys
app.listen(PORT, '127.0.0.1', () => {
console.log(`selfadhesivewallpaper listening on http://127.0.0.1:${PORT}`);
});
})();