feat: complete CMS as fully autonomous self-contained module
Transform CMS from a thin wrapper into a fully self-contained module with all code living within app/modules/cms/: Module Structure: - models/: ContentPage model (canonical location with dynamic discovery) - schemas/: Pydantic schemas for API validation - services/: ContentPageService business logic - exceptions/: Module-specific exceptions - routes/api/: REST API endpoints (admin, vendor, shop) - routes/pages/: HTML page routes (admin, vendor) - templates/cms/: Jinja2 templates (namespaced) - static/: JavaScript files (admin/vendor) - locales/: i18n translations (en, fr, de, lb) Key Changes: - Move ContentPage model to module with dynamic model discovery - Create Pydantic schemas package for request/response validation - Extract API routes from app/api/v1/*/ to module - Extract page routes from admin_pages.py/vendor_pages.py to module - Move static JS files to module with dedicated mount point - Update templates to use cms_static for module assets - Add module static file mounting in main.py - Delete old scattered files (no shims - hard errors on old imports) This establishes the pattern for migrating other modules to be fully autonomous and independently deployable. Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
This commit is contained in:
@@ -1,466 +0,0 @@
|
||||
// noqa: js-006 - async init pattern is safe, loadData has try/catch
|
||||
// static/admin/js/content-page-edit.js
|
||||
|
||||
// Use centralized logger
|
||||
const contentPageEditLog = window.LogConfig.loggers.contentPageEdit || window.LogConfig.createLogger('contentPageEdit');
|
||||
|
||||
// ============================================
|
||||
// CONTENT PAGE EDITOR FUNCTION
|
||||
// ============================================
|
||||
function contentPageEditor(pageId) {
|
||||
return {
|
||||
// Inherit base layout functionality from init-alpine.js
|
||||
...data(),
|
||||
|
||||
// Page identifier for sidebar active state
|
||||
currentPage: 'content-pages',
|
||||
|
||||
// Editor state
|
||||
pageId: pageId,
|
||||
form: {
|
||||
slug: '',
|
||||
title: '',
|
||||
content: '',
|
||||
content_format: 'html',
|
||||
template: 'default',
|
||||
meta_description: '',
|
||||
meta_keywords: '',
|
||||
is_published: false,
|
||||
show_in_header: false,
|
||||
show_in_footer: true,
|
||||
show_in_legal: false,
|
||||
display_order: 0,
|
||||
platform_id: null,
|
||||
vendor_id: null
|
||||
},
|
||||
platforms: [],
|
||||
vendors: [],
|
||||
loading: false,
|
||||
loadingPlatforms: false,
|
||||
loadingVendors: false,
|
||||
saving: false,
|
||||
error: null,
|
||||
successMessage: null,
|
||||
|
||||
// ========================================
|
||||
// HOMEPAGE SECTIONS STATE
|
||||
// ========================================
|
||||
supportedLanguages: ['fr', 'de', 'en'],
|
||||
defaultLanguage: 'fr',
|
||||
currentLang: 'fr',
|
||||
openSection: null,
|
||||
sectionsLoaded: false,
|
||||
languageNames: {
|
||||
en: 'English',
|
||||
fr: 'Français',
|
||||
de: 'Deutsch',
|
||||
lb: 'Lëtzebuergesch'
|
||||
},
|
||||
sections: {
|
||||
hero: {
|
||||
enabled: true,
|
||||
badge_text: { translations: {} },
|
||||
title: { translations: {} },
|
||||
subtitle: { translations: {} },
|
||||
background_type: 'gradient',
|
||||
buttons: []
|
||||
},
|
||||
features: {
|
||||
enabled: true,
|
||||
title: { translations: {} },
|
||||
subtitle: { translations: {} },
|
||||
features: [],
|
||||
layout: 'grid'
|
||||
},
|
||||
pricing: {
|
||||
enabled: true,
|
||||
title: { translations: {} },
|
||||
subtitle: { translations: {} },
|
||||
use_subscription_tiers: true
|
||||
},
|
||||
cta: {
|
||||
enabled: true,
|
||||
title: { translations: {} },
|
||||
subtitle: { translations: {} },
|
||||
buttons: [],
|
||||
background_type: 'gradient'
|
||||
}
|
||||
},
|
||||
|
||||
// Initialize
|
||||
async init() {
|
||||
contentPageEditLog.info('=== CONTENT PAGE EDITOR INITIALIZING ===');
|
||||
contentPageEditLog.info('Page ID:', this.pageId);
|
||||
|
||||
// Prevent multiple initializations
|
||||
if (window._contentPageEditInitialized) {
|
||||
contentPageEditLog.warn('Content page editor already initialized, skipping...');
|
||||
return;
|
||||
}
|
||||
window._contentPageEditInitialized = true;
|
||||
|
||||
// Load platforms and vendors for dropdowns
|
||||
await Promise.all([this.loadPlatforms(), this.loadVendors()]);
|
||||
|
||||
if (this.pageId) {
|
||||
// Edit mode - load existing page
|
||||
contentPageEditLog.group('Loading page for editing');
|
||||
await this.loadPage();
|
||||
contentPageEditLog.groupEnd();
|
||||
|
||||
// Load sections if this is a homepage
|
||||
if (this.form.slug === 'home') {
|
||||
await this.loadSections();
|
||||
}
|
||||
} else {
|
||||
// Create mode - use default values
|
||||
contentPageEditLog.info('Create mode - using default form values');
|
||||
}
|
||||
|
||||
contentPageEditLog.info('=== CONTENT PAGE EDITOR INITIALIZATION COMPLETE ===');
|
||||
},
|
||||
|
||||
// Check if we should show section editor (property, not getter for Alpine compatibility)
|
||||
isHomepage: false,
|
||||
|
||||
// Update isHomepage when slug changes
|
||||
updateIsHomepage() {
|
||||
this.isHomepage = this.form.slug === 'home';
|
||||
},
|
||||
|
||||
// Load platforms for dropdown
|
||||
async loadPlatforms() {
|
||||
this.loadingPlatforms = true;
|
||||
try {
|
||||
contentPageEditLog.info('Loading platforms...');
|
||||
const response = await apiClient.get('/admin/platforms?is_active=true');
|
||||
const data = response.data || response;
|
||||
this.platforms = data.platforms || data.items || data || [];
|
||||
contentPageEditLog.info(`Loaded ${this.platforms.length} platforms`);
|
||||
|
||||
// Set default platform if not editing and no platform selected
|
||||
if (!this.pageId && !this.form.platform_id && this.platforms.length > 0) {
|
||||
this.form.platform_id = this.platforms[0].id;
|
||||
}
|
||||
} catch (err) {
|
||||
contentPageEditLog.error('Error loading platforms:', err);
|
||||
this.platforms = [];
|
||||
} finally {
|
||||
this.loadingPlatforms = false;
|
||||
}
|
||||
},
|
||||
|
||||
// Load vendors for dropdown
|
||||
async loadVendors() {
|
||||
this.loadingVendors = true;
|
||||
try {
|
||||
contentPageEditLog.info('Loading vendors...');
|
||||
const response = await apiClient.get('/admin/vendors?is_active=true&limit=100');
|
||||
const data = response.data || response;
|
||||
this.vendors = data.vendors || data.items || data || [];
|
||||
contentPageEditLog.info(`Loaded ${this.vendors.length} vendors`);
|
||||
} catch (err) {
|
||||
contentPageEditLog.error('Error loading vendors:', err);
|
||||
this.vendors = [];
|
||||
} finally {
|
||||
this.loadingVendors = false;
|
||||
}
|
||||
},
|
||||
|
||||
// Load existing page
|
||||
async loadPage() {
|
||||
this.loading = true;
|
||||
this.error = null;
|
||||
|
||||
try {
|
||||
contentPageEditLog.info(`Fetching page ${this.pageId}...`);
|
||||
|
||||
const response = await apiClient.get(`/admin/content-pages/${this.pageId}`);
|
||||
|
||||
contentPageEditLog.debug('API Response:', response);
|
||||
|
||||
if (!response) {
|
||||
throw new Error('Invalid API response');
|
||||
}
|
||||
|
||||
// Handle response - API returns object directly
|
||||
const page = response.data || response;
|
||||
this.form = {
|
||||
slug: page.slug || '',
|
||||
title: page.title || '',
|
||||
content: page.content || '',
|
||||
content_format: page.content_format || 'html',
|
||||
template: page.template || 'default',
|
||||
meta_description: page.meta_description || '',
|
||||
meta_keywords: page.meta_keywords || '',
|
||||
is_published: page.is_published || false,
|
||||
show_in_header: page.show_in_header || false,
|
||||
show_in_footer: page.show_in_footer !== undefined ? page.show_in_footer : true,
|
||||
show_in_legal: page.show_in_legal || false,
|
||||
display_order: page.display_order || 0,
|
||||
platform_id: page.platform_id,
|
||||
vendor_id: page.vendor_id
|
||||
};
|
||||
|
||||
contentPageEditLog.info('Page loaded successfully');
|
||||
|
||||
// Update computed properties after loading
|
||||
this.updateIsHomepage();
|
||||
|
||||
// Re-initialize Quill editor content after page data is loaded
|
||||
// (Quill may have initialized before loadPage completed)
|
||||
this.syncQuillContent();
|
||||
|
||||
} catch (err) {
|
||||
contentPageEditLog.error('Error loading page:', err);
|
||||
this.error = err.message || 'Failed to load page';
|
||||
} finally {
|
||||
this.loading = false;
|
||||
}
|
||||
},
|
||||
|
||||
// Sync Quill editor content after page data loads
|
||||
// Quill may initialize before loadPage completes, leaving editor empty
|
||||
syncQuillContent(retries = 5) {
|
||||
const quillContainer = document.getElementById('content-editor');
|
||||
|
||||
if (!quillContainer || !quillContainer.__quill) {
|
||||
// Quill not ready yet, retry
|
||||
if (retries > 0) {
|
||||
setTimeout(() => this.syncQuillContent(retries - 1), 100);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
const quill = quillContainer.__quill;
|
||||
if (this.form.content && quill.root.innerHTML !== this.form.content) {
|
||||
quill.root.innerHTML = this.form.content;
|
||||
contentPageEditLog.debug('Synced Quill content after page load');
|
||||
}
|
||||
},
|
||||
|
||||
// ========================================
|
||||
// HOMEPAGE SECTIONS METHODS
|
||||
// ========================================
|
||||
|
||||
// Load sections for homepage
|
||||
async loadSections() {
|
||||
if (!this.pageId || this.form.slug !== 'home') {
|
||||
contentPageEditLog.debug('Skipping section load - not a homepage');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
contentPageEditLog.info('Loading homepage sections...');
|
||||
const response = await apiClient.get(`/admin/content-pages/${this.pageId}/sections`);
|
||||
const data = response.data || response;
|
||||
|
||||
this.supportedLanguages = data.supported_languages || ['fr', 'de', 'en'];
|
||||
this.defaultLanguage = data.default_language || 'fr';
|
||||
this.currentLang = this.defaultLanguage;
|
||||
|
||||
if (data.sections) {
|
||||
this.sections = this.mergeWithDefaults(data.sections);
|
||||
contentPageEditLog.info('Sections loaded:', Object.keys(data.sections));
|
||||
} else {
|
||||
this.initializeEmptySections();
|
||||
contentPageEditLog.info('No sections found - initialized empty structure');
|
||||
}
|
||||
|
||||
this.sectionsLoaded = true;
|
||||
} catch (err) {
|
||||
contentPageEditLog.error('Error loading sections:', err);
|
||||
}
|
||||
},
|
||||
|
||||
// Merge loaded sections with default structure
|
||||
mergeWithDefaults(loadedSections) {
|
||||
const defaults = this.getDefaultSectionStructure();
|
||||
|
||||
// Deep merge each section
|
||||
for (const key of ['hero', 'features', 'pricing', 'cta']) {
|
||||
if (loadedSections[key]) {
|
||||
defaults[key] = { ...defaults[key], ...loadedSections[key] };
|
||||
}
|
||||
}
|
||||
|
||||
return defaults;
|
||||
},
|
||||
|
||||
// Get default section structure
|
||||
getDefaultSectionStructure() {
|
||||
const emptyTranslations = () => {
|
||||
const t = {};
|
||||
this.supportedLanguages.forEach(lang => t[lang] = '');
|
||||
return { translations: t };
|
||||
};
|
||||
|
||||
return {
|
||||
hero: {
|
||||
enabled: true,
|
||||
badge_text: emptyTranslations(),
|
||||
title: emptyTranslations(),
|
||||
subtitle: emptyTranslations(),
|
||||
background_type: 'gradient',
|
||||
buttons: []
|
||||
},
|
||||
features: {
|
||||
enabled: true,
|
||||
title: emptyTranslations(),
|
||||
subtitle: emptyTranslations(),
|
||||
features: [],
|
||||
layout: 'grid'
|
||||
},
|
||||
pricing: {
|
||||
enabled: true,
|
||||
title: emptyTranslations(),
|
||||
subtitle: emptyTranslations(),
|
||||
use_subscription_tiers: true
|
||||
},
|
||||
cta: {
|
||||
enabled: true,
|
||||
title: emptyTranslations(),
|
||||
subtitle: emptyTranslations(),
|
||||
buttons: [],
|
||||
background_type: 'gradient'
|
||||
}
|
||||
};
|
||||
},
|
||||
|
||||
// Initialize empty sections for all languages
|
||||
initializeEmptySections() {
|
||||
this.sections = this.getDefaultSectionStructure();
|
||||
},
|
||||
|
||||
// Add a button to hero or cta section
|
||||
addButton(sectionName) {
|
||||
const newButton = {
|
||||
text: { translations: {} },
|
||||
url: '',
|
||||
style: 'primary'
|
||||
};
|
||||
this.supportedLanguages.forEach(lang => {
|
||||
newButton.text.translations[lang] = '';
|
||||
});
|
||||
this.sections[sectionName].buttons.push(newButton);
|
||||
contentPageEditLog.debug(`Added button to ${sectionName}`);
|
||||
},
|
||||
|
||||
// Remove a button from hero or cta section
|
||||
removeButton(sectionName, index) {
|
||||
this.sections[sectionName].buttons.splice(index, 1);
|
||||
contentPageEditLog.debug(`Removed button ${index} from ${sectionName}`);
|
||||
},
|
||||
|
||||
// Add a feature card
|
||||
addFeature() {
|
||||
const newFeature = {
|
||||
icon: '',
|
||||
title: { translations: {} },
|
||||
description: { translations: {} }
|
||||
};
|
||||
this.supportedLanguages.forEach(lang => {
|
||||
newFeature.title.translations[lang] = '';
|
||||
newFeature.description.translations[lang] = '';
|
||||
});
|
||||
this.sections.features.features.push(newFeature);
|
||||
contentPageEditLog.debug('Added feature card');
|
||||
},
|
||||
|
||||
// Remove a feature card
|
||||
removeFeature(index) {
|
||||
this.sections.features.features.splice(index, 1);
|
||||
contentPageEditLog.debug(`Removed feature ${index}`);
|
||||
},
|
||||
|
||||
// Save sections
|
||||
async saveSections() {
|
||||
if (!this.pageId || !this.isHomepage) return;
|
||||
|
||||
try {
|
||||
contentPageEditLog.info('Saving sections...');
|
||||
await apiClient.put(`/admin/content-pages/${this.pageId}/sections`, this.sections);
|
||||
contentPageEditLog.info('Sections saved successfully');
|
||||
} catch (err) {
|
||||
contentPageEditLog.error('Error saving sections:', err);
|
||||
throw err;
|
||||
}
|
||||
},
|
||||
|
||||
// Save page (create or update)
|
||||
async savePage() {
|
||||
if (this.saving) return;
|
||||
|
||||
this.saving = true;
|
||||
this.error = null;
|
||||
this.successMessage = null;
|
||||
|
||||
try {
|
||||
contentPageEditLog.info(this.pageId ? 'Updating page...' : 'Creating page...');
|
||||
|
||||
const payload = {
|
||||
slug: this.form.slug,
|
||||
title: this.form.title,
|
||||
content: this.form.content,
|
||||
content_format: this.form.content_format,
|
||||
template: this.form.template,
|
||||
meta_description: this.form.meta_description,
|
||||
meta_keywords: this.form.meta_keywords,
|
||||
is_published: this.form.is_published,
|
||||
show_in_header: this.form.show_in_header,
|
||||
show_in_footer: this.form.show_in_footer,
|
||||
show_in_legal: this.form.show_in_legal,
|
||||
display_order: this.form.display_order,
|
||||
platform_id: this.form.platform_id,
|
||||
vendor_id: this.form.vendor_id
|
||||
};
|
||||
|
||||
contentPageEditLog.debug('Payload:', payload);
|
||||
|
||||
let response;
|
||||
if (this.pageId) {
|
||||
// Update existing page
|
||||
response = await apiClient.put(`/admin/content-pages/${this.pageId}`, payload);
|
||||
|
||||
// Also save sections if this is a homepage
|
||||
if (this.isHomepage && this.sectionsLoaded) {
|
||||
await this.saveSections();
|
||||
}
|
||||
|
||||
this.successMessage = 'Page updated successfully!';
|
||||
contentPageEditLog.info('Page updated');
|
||||
} else {
|
||||
// Create new page - use vendor or platform endpoint based on selection
|
||||
const endpoint = this.form.vendor_id
|
||||
? '/admin/content-pages/vendor'
|
||||
: '/admin/content-pages/platform';
|
||||
response = await apiClient.post(endpoint, payload);
|
||||
this.successMessage = 'Page created successfully!';
|
||||
contentPageEditLog.info('Page created', { endpoint, vendor_id: this.form.vendor_id });
|
||||
|
||||
// Redirect to edit page after creation
|
||||
const pageData = response.data || response;
|
||||
if (pageData && pageData.id) {
|
||||
setTimeout(() => {
|
||||
window.location.href = `/admin/content-pages/${pageData.id}/edit`;
|
||||
}, 1500);
|
||||
}
|
||||
}
|
||||
|
||||
// Clear success message after 3 seconds
|
||||
setTimeout(() => {
|
||||
this.successMessage = null;
|
||||
}, 3000);
|
||||
|
||||
} catch (err) {
|
||||
contentPageEditLog.error('Error saving page:', err);
|
||||
this.error = err.message || 'Failed to save page';
|
||||
|
||||
// Scroll to top to show error
|
||||
window.scrollTo({ top: 0, behavior: 'smooth' });
|
||||
} finally {
|
||||
this.saving = false;
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
@@ -1,266 +0,0 @@
|
||||
// noqa: js-006 - async init pattern is safe, loadData has try/catch
|
||||
// static/admin/js/content-pages.js
|
||||
|
||||
// Use centralized logger
|
||||
const contentPagesLog = window.LogConfig.loggers.contentPages || window.LogConfig.createLogger('contentPages');
|
||||
|
||||
// ============================================
|
||||
// CONTENT PAGES MANAGER FUNCTION
|
||||
// ============================================
|
||||
function contentPagesManager() {
|
||||
return {
|
||||
// Inherit base layout functionality from init-alpine.js
|
||||
...data(),
|
||||
|
||||
// Page identifier for sidebar active state
|
||||
currentPage: 'content-pages',
|
||||
|
||||
// Content pages specific state
|
||||
allPages: [],
|
||||
platforms: [],
|
||||
loading: false,
|
||||
error: null,
|
||||
|
||||
// Tabs and filters
|
||||
activeTab: 'all', // all, platform_marketing, vendor_defaults, vendor_overrides
|
||||
searchQuery: '',
|
||||
selectedPlatform: '', // Platform code filter
|
||||
|
||||
// Initialize
|
||||
async init() {
|
||||
contentPagesLog.info('=== CONTENT PAGES MANAGER INITIALIZING ===');
|
||||
|
||||
// Prevent multiple initializations
|
||||
if (window._contentPagesInitialized) {
|
||||
contentPagesLog.warn('Content pages manager already initialized, skipping...');
|
||||
return;
|
||||
}
|
||||
window._contentPagesInitialized = true;
|
||||
|
||||
contentPagesLog.group('Loading data');
|
||||
await Promise.all([
|
||||
this.loadPages(),
|
||||
this.loadPlatforms()
|
||||
]);
|
||||
contentPagesLog.groupEnd();
|
||||
|
||||
// Check for platform filter in URL (support both 'platform' and 'platform_code')
|
||||
const urlParams = new URLSearchParams(window.location.search);
|
||||
const platformParam = urlParams.get('platform_code') || urlParams.get('platform');
|
||||
if (platformParam) {
|
||||
this.selectedPlatform = platformParam;
|
||||
}
|
||||
|
||||
// Check for slug param - if specified, redirect to edit page
|
||||
const slugParam = urlParams.get('slug');
|
||||
if (slugParam && platformParam) {
|
||||
await this.redirectToEditIfSlugMatches(platformParam, slugParam);
|
||||
}
|
||||
|
||||
contentPagesLog.info('=== CONTENT PAGES MANAGER INITIALIZATION COMPLETE ===');
|
||||
},
|
||||
|
||||
// Computed: Platform Marketing pages (is_platform_page=true, vendor_id=null)
|
||||
get platformMarketingPages() {
|
||||
return this.allPages.filter(page => page.is_platform_page && !page.vendor_id);
|
||||
},
|
||||
|
||||
// Computed: Vendor Default pages (is_platform_page=false, vendor_id=null)
|
||||
get vendorDefaultPages() {
|
||||
return this.allPages.filter(page => !page.is_platform_page && !page.vendor_id);
|
||||
},
|
||||
|
||||
// Computed: Vendor Override pages (vendor_id is set)
|
||||
get vendorOverridePages() {
|
||||
return this.allPages.filter(page => page.vendor_id);
|
||||
},
|
||||
|
||||
// Legacy computed (for backward compatibility)
|
||||
get platformPages() {
|
||||
return [...this.platformMarketingPages, ...this.vendorDefaultPages];
|
||||
},
|
||||
|
||||
get vendorPages() {
|
||||
return this.vendorOverridePages;
|
||||
},
|
||||
|
||||
// Computed: Filtered pages based on active tab, platform, and search
|
||||
get filteredPages() {
|
||||
let pages = [];
|
||||
|
||||
// Filter by tab (three-tier system)
|
||||
if (this.activeTab === 'platform_marketing') {
|
||||
pages = this.platformMarketingPages;
|
||||
} else if (this.activeTab === 'vendor_defaults') {
|
||||
pages = this.vendorDefaultPages;
|
||||
} else if (this.activeTab === 'vendor_overrides') {
|
||||
pages = this.vendorOverridePages;
|
||||
} else {
|
||||
pages = this.allPages;
|
||||
}
|
||||
|
||||
// Filter by selected platform
|
||||
if (this.selectedPlatform) {
|
||||
pages = pages.filter(page =>
|
||||
page.platform_code === this.selectedPlatform
|
||||
);
|
||||
}
|
||||
|
||||
// Filter by search query
|
||||
if (this.searchQuery) {
|
||||
const query = this.searchQuery.toLowerCase();
|
||||
pages = pages.filter(page =>
|
||||
page.title.toLowerCase().includes(query) ||
|
||||
page.slug.toLowerCase().includes(query) ||
|
||||
(page.vendor_name && page.vendor_name.toLowerCase().includes(query)) ||
|
||||
(page.platform_name && page.platform_name.toLowerCase().includes(query))
|
||||
);
|
||||
}
|
||||
|
||||
// Sort by display_order, then title
|
||||
return pages.sort((a, b) => {
|
||||
if (a.display_order !== b.display_order) {
|
||||
return a.display_order - b.display_order;
|
||||
}
|
||||
return a.title.localeCompare(b.title);
|
||||
});
|
||||
},
|
||||
|
||||
// Load all content pages
|
||||
async loadPages() {
|
||||
this.loading = true;
|
||||
this.error = null;
|
||||
|
||||
try {
|
||||
contentPagesLog.info('Fetching all content pages...');
|
||||
|
||||
// Fetch all pages (platform + vendor, published + unpublished)
|
||||
const response = await apiClient.get('/admin/content-pages/?include_unpublished=true');
|
||||
|
||||
contentPagesLog.debug('API Response:', response);
|
||||
|
||||
if (!response) {
|
||||
throw new Error('Invalid API response');
|
||||
}
|
||||
|
||||
// Handle response - API returns array directly
|
||||
this.allPages = Array.isArray(response) ? response : (response.data || response.items || []);
|
||||
contentPagesLog.info(`Loaded ${this.allPages.length} pages`);
|
||||
|
||||
} catch (err) {
|
||||
contentPagesLog.error('Error loading content pages:', err);
|
||||
this.error = err.message || 'Failed to load content pages';
|
||||
} finally {
|
||||
this.loading = false;
|
||||
}
|
||||
},
|
||||
|
||||
// Load platforms for filter dropdown
|
||||
async loadPlatforms() {
|
||||
try {
|
||||
contentPagesLog.info('Fetching platforms...');
|
||||
const response = await apiClient.get('/admin/platforms');
|
||||
this.platforms = response.platforms || [];
|
||||
contentPagesLog.info(`Loaded ${this.platforms.length} platforms`);
|
||||
} catch (err) {
|
||||
contentPagesLog.error('Error loading platforms:', err);
|
||||
// Non-critical - don't set error state
|
||||
}
|
||||
},
|
||||
|
||||
// Redirect to edit page if a specific slug is requested
|
||||
async redirectToEditIfSlugMatches(platformCode, slug) {
|
||||
contentPagesLog.info(`Looking for page with platform=${platformCode}, slug=${slug}`);
|
||||
|
||||
// Find the page matching the platform and slug
|
||||
const matchingPage = this.allPages.find(page =>
|
||||
page.platform_code === platformCode && page.slug === slug
|
||||
);
|
||||
|
||||
if (matchingPage) {
|
||||
contentPagesLog.info(`Found matching page: ${matchingPage.id}, redirecting to edit...`);
|
||||
window.location.href = `/admin/content-pages/${matchingPage.id}/edit`;
|
||||
} else {
|
||||
contentPagesLog.warn(`No page found for platform=${platformCode}, slug=${slug}`);
|
||||
// Show a toast and offer to create
|
||||
if (slug === 'home') {
|
||||
// Offer to create homepage
|
||||
if (confirm(`No homepage found for ${platformCode}. Would you like to create one?`)) {
|
||||
window.location.href = `/admin/content-pages/create?platform_code=${platformCode}&slug=home&is_platform_page=true`;
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
// Get page tier label (three-tier system)
|
||||
getPageTierLabel(page) {
|
||||
if (page.vendor_id) {
|
||||
return 'Vendor Override';
|
||||
} else if (page.is_platform_page) {
|
||||
return 'Platform Marketing';
|
||||
} else {
|
||||
return 'Vendor Default';
|
||||
}
|
||||
},
|
||||
|
||||
// Get page tier CSS class (three-tier system)
|
||||
getPageTierClass(page) {
|
||||
if (page.vendor_id) {
|
||||
// Vendor Override - purple
|
||||
return 'bg-purple-100 text-purple-800 dark:bg-purple-900 dark:text-purple-200';
|
||||
} else if (page.is_platform_page) {
|
||||
// Platform Marketing - blue
|
||||
return 'bg-blue-100 text-blue-800 dark:bg-blue-900 dark:text-blue-200';
|
||||
} else {
|
||||
// Vendor Default - teal
|
||||
return 'bg-teal-100 text-teal-800 dark:bg-teal-900 dark:text-teal-200';
|
||||
}
|
||||
},
|
||||
|
||||
// Delete a page
|
||||
async deletePage(page) {
|
||||
if (!confirm(`Are you sure you want to delete "${page.title}"?`)) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
contentPagesLog.info(`Deleting page: ${page.id}`);
|
||||
|
||||
await apiClient.delete(`/admin/content-pages/${page.id}`);
|
||||
|
||||
// Remove from local array
|
||||
this.allPages = this.allPages.filter(p => p.id !== page.id);
|
||||
|
||||
contentPagesLog.info('Page deleted successfully');
|
||||
|
||||
} catch (err) {
|
||||
contentPagesLog.error('Error deleting page:', err);
|
||||
Utils.showToast(`Failed to delete page: ${err.message}`, 'error');
|
||||
}
|
||||
},
|
||||
|
||||
// Format date helper
|
||||
formatDate(dateString) {
|
||||
if (!dateString) return '—';
|
||||
|
||||
const date = new Date(dateString);
|
||||
const now = new Date();
|
||||
const diffMs = now - date;
|
||||
const diffDays = Math.floor(diffMs / (1000 * 60 * 60 * 24));
|
||||
|
||||
if (diffDays === 0) {
|
||||
return 'Today';
|
||||
} else if (diffDays === 1) {
|
||||
return 'Yesterday';
|
||||
} else if (diffDays < 7) {
|
||||
return `${diffDays} days ago`;
|
||||
} else {
|
||||
return date.toLocaleDateString('en-US', {
|
||||
year: 'numeric',
|
||||
month: 'short',
|
||||
day: 'numeric'
|
||||
});
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
Reference in New Issue
Block a user