diff --git "a/server.js" "b/server.js" --- "a/server.js" +++ "b/server.js" @@ -18,7 +18,7 @@ const Jimp = require('jimp'); const fs = require('fs'); const fetch = global.fetch || require('node-fetch'); const pdfParse = require('pdf-parse'); - +const { createHash } = require('crypto'); const path = require('path'); require('jspdf-autotable'); @@ -76,6 +76,9 @@ const OAuth2Strategy = require('passport-oauth2').Strategy; // const jsPDF = require('jspdf'); const webpush = require('web-push'); +const { Document, Packer, Paragraph, TextRun, Table, TableRow, TableCell, WidthType } = require('docx'); +const ShortcodeService = require('./services/ShortcodeService'); + // ❌ احذف هذا السطر لأنه مكرر (logger عرفته فوق) // const logger = winston.createLogger({...}); @@ -262,8 +265,12 @@ const excludedPaths = [ '/api/store/products', '/api/store/:username/products', '/api/store/products/:productId', - - + '/api/store/theme', + '/api/store/theme/reset', + '/api/store/shortcodes/parse', + '/api/store/shortcodes', + '/api/store/shortcodes/:id', + '/api/store/shortcodes/preview', '/api/cart', '/api/cart/add', @@ -1540,46 +1547,145 @@ orderSchema.index({ status: 1 }); const Order = mongoose.model('Order', orderSchema); // 3. نموذج إعدادات المتجر (Store Settings) +/** + * نموذج إعدادات المتجر - يدعم القوالب، الاشتراكات، الإحصائيات المتقدمة + * @version 3.0.0 + */ + const storeSettingsSchema = new mongoose.Schema({ - userId: { type: mongoose.Schema.Types.ObjectId, ref: 'User', required: true, unique: true }, - enabled: { type: Boolean, default: false }, - storeName: { type: String, default: '' }, + // ============================================ + // المعلومات الأساسية + // ============================================ + userId: { + type: mongoose.Schema.Types.ObjectId, + ref: 'User', + required: true, + unique: true, + index: true + }, + enabled: { + type: Boolean, + default: false, + index: true + }, + + // ============================================ + // معلومات المتجر العامة + // ============================================ + storeName: { type: String, default: '', trim: true, maxlength: 100 }, storeLogo: { type: String, default: '' }, storeBanner: { type: String, default: '' }, - storeDescription: { type: String, default: '' }, - currency: { type: String, default: 'USD' }, + storeDescription: { type: String, default: '', maxlength: 500 }, + contactEmail: { type: String, default: '', lowercase: true, trim: true }, + + // ============================================ + // العملة والإعدادات المالية + // ============================================ + currency: { type: String, default: 'USD', uppercase: true }, currencySymbol: { type: String, default: '$' }, - contactEmail: { type: String, default: '' }, - // 🎨 إعدادات التصميم (الحقول الجديدة) - primaryColor: { type: String, default: '#3b82f6' }, - secondaryColor: { type: String, default: '#8b5cf6' }, - fontFamily: { type: String, default: 'Inter, sans-serif' }, - borderRadius: { type: Number, default: 16 }, - shadowType: { type: String, default: 'md' }, - animationType: { type: String, default: 'lift' }, - glassEffect: { type: Boolean, default: false }, - backgroundType: { type: String, default: 'default' }, - backgroundValue: { type: String, default: '' }, - customCss: { type: String, default: '' }, - productViewType: { type: String, enum: ['modal', 'page'], default: 'modal' }, - pagesOrder: { - type: mongoose.Schema.Types.Mixed, - default: { - products: 1, - about: 2, - contact: 3 - } + + // إعدادات الدفع المتقدمة + paymentSettings: { + currencyPosition: { type: String, enum: ['left', 'right'], default: 'left' }, + decimalPlaces: { type: Number, default: 2, min: 0, max: 4 }, + thousandsSeparator: { type: String, default: ',' }, + decimalSeparator: { type: String, default: '.' }, + enableCOD: { type: Boolean, default: false }, + enableInstallments: { type: Boolean, default: false }, + installmentProviders: [{ type: String }], + minOrderAmount: { type: Number, default: 0 }, + freeShippingThreshold: { type: Number, default: 0 }, + taxRate: { type: Number, default: 0, min: 0, max: 100 }, + shippingCost: { type: Number, default: 0 } }, - + // طرق الدفع paymentMethods: [{ - type: { type: String, enum: ['paypal', 'stripe', 'vodafone', 'instapay', 'bank'] }, + type: { type: String, enum: ['paypal', 'stripe', 'vodafone', 'instapay', 'bank', 'cod'] }, label: { type: String }, details: { type: mongoose.Schema.Types.Mixed }, - isActive: { type: Boolean, default: true } + isActive: { type: Boolean, default: true }, + createdAt: { type: Date, default: Date.now } }], - // Page Builder (سحب وإفلات) + // ============================================ + // 🎨 إعدادات التصميم (Theme) + // ============================================ + activeThemeId: { + type: mongoose.Schema.Types.ObjectId, + ref: 'StoreTheme', + default: null + }, + + // الألوان الأساسية + primaryColor: { type: String, default: '#3b82f6', match: /^#[0-9A-Fa-f]{6}$/ }, + secondaryColor: { type: String, default: '#8b5cf6', match: /^#[0-9A-Fa-f]{6}$/ }, + + // الألوان الموسعة + colorPalette: { + primaryHover: { type: String, default: '#2563eb' }, + secondaryHover: { type: String, default: '#7c3aed' }, + buttonText: { type: String, default: '#ffffff' }, + linkColor: { type: String, default: '#3b82f6' }, + linkHover: { type: String, default: '#2563eb' }, + headingColor: { type: String, default: '#1f2937' }, + bodyColor: { type: String, default: '#374151' }, + borderColor: { type: String, default: '#e5e7eb' }, + successColor: { type: String, default: '#10b981' }, + errorColor: { type: String, default: '#ef4444' }, + warningColor: { type: String, default: '#f59e0b' } + }, + + // الخطوط + fontFamily: { type: String, default: 'Inter, sans-serif' }, + typography: { + headingFont: { type: String, default: 'Inter, sans-serif' }, + baseFontSize: { type: String, default: '16px', match: /^\d+(px|rem)$/ }, + enableGoogleFonts: { type: Boolean, default: true } + }, + + // التخطيط + borderRadius: { type: Number, default: 16, min: 0, max: 48 }, + shadowType: { type: String, enum: ['none', 'sm', 'md', 'lg', 'xl'], default: 'md' }, + animationType: { type: String, enum: ['none', 'lift', 'scale', 'glow'], default: 'lift' }, + glassEffect: { type: Boolean, default: false }, + + // الخلفية + backgroundType: { + type: String, + enum: ['default', 'dots', 'grid', 'cross', 'gradient', 'image'], + default: 'default' + }, + backgroundValue: { type: String, default: '' }, + + // CSS مخصص + customCss: { type: String, default: '', maxlength: 100000 }, + + // إعدادات التخطيط المتقدمة + layoutSettings: { + headerLayout: { type: String, enum: ['default', 'centered', 'minimal', 'transparent'], default: 'default' }, + footerLayout: { type: String, enum: ['default', 'minimal', 'columns'], default: 'default' }, + sidebarPosition: { type: String, enum: ['left', 'right', 'none'], default: 'none' }, + productsPerRowMobile: { type: Number, default: 2, min: 1, max: 2 }, + productsPerRowTablet: { type: Number, default: 3, min: 1, max: 4 }, + productsPerRowDesktop: { type: Number, default: 4, min: 1, max: 6 }, + enableStickyAddToCart: { type: Boolean, default: true }, + enableQuickView: { type: Boolean, default: true }, + enableCompareProducts: { type: Boolean, default: false }, + enableWishlist: { type: Boolean, default: false }, + enableRecentlyViewed: { type: Boolean, default: true }, + enableProductReviews: { type: Boolean, default: true } + }, + + // ============================================ + // سلوك المنتجات + // ============================================ + productViewType: { type: String, enum: ['modal', 'page'], default: 'modal' }, + autoApproveReviews: { type: Boolean, default: false }, + + // ============================================ + // Page Builder + // ============================================ pageBuilder: { type: mongoose.Schema.Types.Mixed, default: { @@ -1594,170 +1700,1847 @@ const storeSettingsSchema = new mongoose.Schema({ ] } }, - - productsCount: { - type: Number, - default: 0 - }, - - followersCount: { - type: Number, - default: 0 - }, - - averageRating: { - type: Number, - default: 0 + + pagesOrder: { + type: mongoose.Schema.Types.Mixed, + default: { + products: 1, + about: 2, + contact: 3 + } }, - - // Social Links (خاصة بالمتجر) + // ============================================ + // التواصل الاجتماعي + // ============================================ socialLinks: { instagram: { type: String, default: '' }, facebook: { type: String, default: '' }, twitter: { type: String, default: '' }, - tiktok: { type: String, default: '' } + tiktok: { type: String, default: '' }, + linkedin: { type: String, default: '' }, + youtube: { type: String, default: '' }, + whatsapp: { type: String, default: '' }, + telegram: { type: String, default: '' } }, - createdAt: { type: Date, default: Date.now }, + // ============================================ + // SEO والإحصائيات + // ============================================ + seoSettings: { + metaTitleTemplate: { type: String, default: '{{title}} | {{storeName}}' }, + metaDescriptionTemplate: { type: String, default: '' }, + productTitleTemplate: { type: String, default: '{{title}} - {{storeName}}' }, + enableBreadcrumbs: { type: Boolean, default: true }, + sitemapEnabled: { type: Boolean, default: true }, + robotsTxt: { type: String, default: '' }, + canonicalUrl: { type: String, default: '' } + }, + + socialMediaSettings: { + facebookPixel: { type: String, default: '' }, + googleAnalytics: { type: String, default: '' }, + tiktokPixel: { type: String, default: '' }, + twitterPixel: { type: String, default: '' }, + linkedInInsight: { type: String, default: '' } + }, + + // ============================================ + // العلامة التجارية + // ============================================ + branding: { + favicon: { type: String, default: '' }, + watermark: { type: String, default: '' }, + customDomain: { type: String, default: '' }, + customDomainVerified: { type: Boolean, default: false }, + removeBranding: { type: Boolean, default: false } // إزالة علامة MGZon + }, + + // ============================================ + // إعدادات الأداء + // ============================================ + performanceSettings: { + enableLazyLoad: { type: Boolean, default: true }, + enableImageOptimization: { type: Boolean, default: true }, + enablePreload: { type: Boolean, default: true }, + cacheTTL: { type: Number, default: 3600 }, // ثواني + enableServiceWorker: { type: Boolean, default: false } + }, + + // ============================================ + // إعدادات الإشعارات + // ============================================ + notificationSettings: { + newOrderEmail: { type: Boolean, default: true }, + newOrderSMS: { type: Boolean, default: false }, + lowStockAlert: { type: Boolean, default: true }, + lowStockThreshold: { type: Number, default: 5 }, + dailySummaryEmail: { type: Boolean, default: false }, + weeklyReportEmail: { type: Boolean, default: true }, + sendInvoiceEmail: { type: Boolean, default: true } + }, + + // ============================================ + // إعدادات الأمان + // ============================================ + securitySettings: { + enableCaptcha: { type: Boolean, default: false }, + captchaSiteKey: { type: String, default: '' }, + enable2FA: { type: Boolean, default: false }, + ipWhitelist: [{ type: String }], + ipBlacklist: [{ type: String }], + rateLimitPerMinute: { type: Number, default: 60 } + }, + + // ============================================ + // الإحصائيات (مدمجة) + // ============================================ + productsCount: { type: Number, default: 0 }, + followersCount: { type: Number, default: 0 }, + averageRating: { type: Number, default: 0, min: 0, max: 5 }, + + extendedStats: { + totalViews: { type: Number, default: 0 }, + totalUniqueVisitors: { type: Number, default: 0 }, + totalOrders: { type: Number, default: 0 }, + totalSales: { type: Number, default: 0 }, + totalShares: { type: Number, default: 0 }, + conversionRate: { type: Number, default: 0 }, + averageOrderValue: { type: Number, default: 0 }, + topReferrers: [{ source: String, count: Number }], + dailyStats: { type: mongoose.Schema.Types.Mixed, default: {} }, + monthlyStats: { type: mongoose.Schema.Types.Mixed, default: {} } + }, + + // ============================================ + // حدود المنتجات (بناءً على الاشتراك) + // ============================================ + limits: { + maxProducts: { type: Number, default: 0 }, + maxDigitalProducts: { type: Number, default: 0 }, + maxProjects: { type: Number, default: 0 }, + maxServices: { type: Number, default: 0 }, + maxPages: { type: Number, default: 0 }, + maxStorageMB: { type: Number, default: 100 }, + maxBandwidthGB: { type: Number, default: 10 } + }, + + // ============================================ + // حالة الاشتراك (مخزنة مؤقتاً) + // ============================================ + subscriptionStatus: { + isActive: { type: Boolean, default: false }, + planId: { type: mongoose.Schema.Types.ObjectId, ref: 'SubscriptionPlan' }, + planName: { type: String, default: '' }, + expiresAt: { type: Date }, + cachedAt: { type: Date, default: Date.now } + }, + + // ============================================ + // أكواد الخصم العامة للمتجر + // ============================================ + storeCoupons: [{ + code: { type: String, uppercase: true, trim: true }, + discount: { type: Number, min: 0, max: 100 }, + discountType: { type: String, enum: ['percentage', 'fixed'], default: 'percentage' }, + minPurchase: { type: Number, default: 0 }, + maxDiscount: { type: Number }, + validFrom: { type: Date, default: Date.now }, + validUntil: { type: Date }, + usageLimit: { type: Number }, + usedCount: { type: Number, default: 0 }, + isActive: { type: Boolean, default: true } + }], + + // ============================================ + // مناطق الشحن + // ============================================ + shippingZones: [{ + name: { type: String, required: true }, + countries: [{ type: String }], + cities: [{ type: String }], + cost: { type: Number, default: 0 }, + freeShippingAbove: { type: Number, default: 0 }, + estimatedDays: { type: String, default: '3-7 business days' } + }], + + // ============================================ + // إعدادات النسخ الاحتياطي + // ============================================ + backupSettings: { + autoBackup: { type: Boolean, default: false }, + backupFrequency: { type: String, enum: ['daily', 'weekly', 'monthly'], default: 'weekly' }, + lastBackupAt: { type: Date }, + backupSize: { type: Number, default: 0 }, + backupLocation: { type: String, default: '' } + }, + + // ============================================ + // إعدادات التصدير + // ============================================ + exportSettings: { + enableCSVExport: { type: Boolean, default: true }, + enableJSONExport: { type: Boolean, default: true }, + enablePDFExport: { type: Boolean, default: true }, + exportEmailReports: { type: Boolean, default: false }, + exportEmail: { type: String, default: '' } + }, + + // ============================================ + // إعدادات متقدمة أخرى + // ============================================ + enableGuestCheckout: { type: Boolean, default: true }, + enableCookiesConsent: { type: Boolean, default: true }, + enableTermsCheckbox: { type: Boolean, default: true }, + termsUrl: { type: String, default: '' }, + privacyUrl: { type: String, default: '' }, + + createdAt: { type: Date, default: Date.now, immutable: true }, updatedAt: { type: Date, default: Date.now } +}, { + timestamps: true, + toJSON: { virtuals: true }, + toObject: { virtuals: true } }); -storeSettingsSchema.index({ userId: 1 }); +// ============================================ +// ✅ Indexes محسنة +// ============================================ +storeSettingsSchema.index({ userId: 1 }, { unique: true }); storeSettingsSchema.index({ enabled: 1 }); storeSettingsSchema.index({ storeName: 1 }); storeSettingsSchema.index({ averageRating: -1 }); storeSettingsSchema.index({ productsCount: -1 }); storeSettingsSchema.index({ followersCount: -1 }); storeSettingsSchema.index({ createdAt: -1 }); +storeSettingsSchema.index({ 'subscriptionStatus.isActive': 1 }); +storeSettingsSchema.index({ 'subscriptionStatus.expiresAt': 1 }); +storeSettingsSchema.index({ 'branding.customDomain': 1 }); +storeSettingsSchema.index({ 'extendedStats.totalViews': -1 }); +storeSettingsSchema.index({ 'extendedStats.totalSales': -1 }); -const StoreSettings = mongoose.model('StoreSettings', storeSettingsSchema); +// ============================================ +// ✅ Virtuals +// ============================================ +storeSettingsSchema.virtual('storeUrl').get(function() { + const baseUrl = process.env.BASE_URL || 'https://mgzon-server.hf.space'; + return `${baseUrl}/shop/${this.userId}`; +}); +storeSettingsSchema.virtual('hasCustomTheme').get(function() { + return !!this.activeThemeId; +}); +storeSettingsSchema.virtual('isSubscriptionActive').get(function() { + if (!this.subscriptionStatus.isActive) return false; + if (!this.subscriptionStatus.expiresAt) return true; + return new Date() < this.subscriptionStatus.expiresAt; +}); // ============================================ -// 🗂️ STORE PAGES MODEL - صفحات المتجر المخصصة (محدث بالكامل) +// ✅ Pre-save Middleware // ============================================ -const pageSchema = new mongoose.Schema({ - storeId: { - type: mongoose.Schema.Types.ObjectId, - ref: 'User', - required: true - }, +storeSettingsSchema.pre('save', function(next) { + this.updatedAt = Date.now(); - //基本信息 - slug: { - type: String, - required: true, - lowercase: true, - trim: true, - match: /^[a-z0-9]+(?:-[a-z0-9]+)*$/ // slug صالح: about-us, contact, my-page - }, - title: { - type: String, - required: true, - trim: true, - maxlength: 100 - }, + // تحديث رمز العملة تلقائياً + const currencySymbols = { + 'USD': '$', 'EUR': '€', 'GBP': '£', 'EGP': 'ج.م', + 'SAR': '﷼', 'AED': 'د.إ', 'CAD': 'C$', 'AUD': 'A$', + 'JPY': '¥', 'CNY': '¥', 'INR': '₹', 'BRL': 'R$' + }; - // المحتوى والتخصيص - content: { - type: String, - default: '' - }, // HTML content - css: { - type: String, - default: '' - }, // Custom CSS for this page - js: { - type: String, - default: '' - }, // Custom JavaScript for this page + if (this.currency && currencySymbols[this.currency]) { + this.currencySymbol = currencySymbols[this.currency]; + } - // نوع الصفحة - type: { - type: String, - enum: ['default', 'custom', 'uploaded'], - default: 'custom' - }, - isDefault: { - type: Boolean, - default: false - }, // هل هي صفحة افتراضية (products, about, contact) + // تنظيف الروابط + if (this.socialLinks) { + Object.keys(this.socialLinks).forEach(key => { + if (this.socialLinks[key]) { + this.socialLinks[key] = this.socialLinks[key].trim(); + } + }); + } - // حالة الصفحة - isEnabled: { - type: Boolean, - default: true - }, - order: { - type: Number, - default: 0 - }, + // تنظيف الأكواد المكررة في storeCoupons + if (this.storeCoupons && this.storeCoupons.length > 0) { + const uniqueCodes = new Map(); + for (const coupon of this.storeCoupons) { + if (!uniqueCodes.has(coupon.code)) { + uniqueCodes.set(coupon.code, coupon); + } + } + this.storeCoupons = Array.from(uniqueCodes.values()); + } - // ملف مرفوع (للصفحات المرفوعة) - uploadedFile: { - filename: { type: String }, - originalName: { type: String }, - fileUrl: { type: String }, - fileSize: { type: Number }, - mimeType: { type: String }, - uploadedAt: { type: Date, default: Date.now } + next(); +}); + +// ============================================ +// ✅ Static Methods +// ============================================ + +/** + * جلب أو إنشاء إعدادات المتجر لمستخدم + */ +storeSettingsSchema.statics.getOrCreate = async function(userId) { + let settings = await this.findOne({ userId }); + + if (!settings) { + settings = new this({ userId }); + await settings.save(); + } + + return settings; +}; + +/** + * تحديث إحصائيات المتجر + */ +storeSettingsSchema.statics.updateStats = async function(userId, stats) { + const updateData = {}; + + if (stats.productsCount !== undefined) updateData.productsCount = stats.productsCount; + if (stats.followersCount !== undefined) updateData.followersCount = stats.followersCount; + if (stats.averageRating !== undefined) updateData.averageRating = stats.averageRating; + if (stats.totalViews !== undefined) updateData['extendedStats.totalViews'] = stats.totalViews; + if (stats.totalSales !== undefined) updateData['extendedStats.totalSales'] = stats.totalSales; + if (stats.totalOrders !== undefined) updateData['extendedStats.totalOrders'] = stats.totalOrders; + + return this.findOneAndUpdate( + { userId }, + { $inc: updateData, $set: { updatedAt: Date.now() } }, + { new: true } + ); +}; + +/** + * جلب المتاجر الأكثر مبيعاً + */ +storeSettingsSchema.statics.getTopStores = async function(limit = 10) { + return this.find({ enabled: true }) + .sort({ 'extendedStats.totalSales': -1 }) + .limit(limit) + .select('userId storeName storeLogo productsCount followersCount extendedStats.totalSales'); +}; + +/** + * جلب المتاجر النشطة (مع اشتراك ساري) + */ +storeSettingsSchema.statics.getActiveStores = async function(limit = 50) { + const now = new Date(); + return this.find({ + enabled: true, + 'subscriptionStatus.isActive': true, + $or: [ + { 'subscriptionStatus.expiresAt': { $exists: false } }, + { 'subscriptionStatus.expiresAt': { $gte: now } } + ] + }).limit(limit); +}; + +// ============================================ +// ✅ Instance Methods +// ============================================ + +/** + * تحديث إحصائيات الاشتراك + */ +storeSettingsSchema.methods.updateSubscriptionStatus = async function(subscription) { + this.subscriptionStatus = { + isActive: subscription.status === 'active', + planId: subscription.planId, + planName: subscription.planName, + expiresAt: subscription.endDate, + cachedAt: new Date() + }; + + // تحديث الحدود بناءً على الخطة + if (subscription.plan) { + this.limits = { + maxProducts: subscription.plan.features?.maxProducts || 0, + maxDigitalProducts: subscription.plan.features?.maxDigitalProducts || 0, + maxProjects: subscription.plan.features?.maxProjects || 0, + maxServices: subscription.plan.features?.maxServices || 0, + maxPages: subscription.plan.features?.maxPages || 0, + maxStorageMB: subscription.plan.features?.maxStorageMB || 100, + maxBandwidthGB: subscription.plan.features?.maxBandwidthGB || 10 + }; + + this.branding.removeBranding = subscription.plan.features?.removeBranding || false; + } + + await this.save(); +}; + +/** + * التحقق من وجود منتج في المتجر + */ +storeSettingsSchema.methods.canAddProduct = async function(type) { + if (!this.subscriptionStatus.isActive) return false; + + const currentCounts = { + product: this.productsCount, + digital: await mongoose.model('Product').countDocuments({ userId: this.userId, type: 'digital', isActive: true }), + project: await mongoose.model('Product').countDocuments({ userId: this.userId, type: 'project', isActive: true }), + service: await mongoose.model('Product').countDocuments({ userId: this.userId, type: 'service', isActive: true }) + }; + + const limits = this.limits; + + if (limits.maxProducts > 0 && currentCounts.product >= limits.maxProducts) { + return false; + } + + if (type === 'digital' && limits.maxDigitalProducts > 0 && currentCounts.digital >= limits.maxDigitalProducts) { + return false; + } + + if (type === 'project' && limits.maxProjects > 0 && currentCounts.project >= limits.maxProjects) { + return false; + } + + if (type === 'service' && limits.maxServices > 0 && currentCounts.service >= limits.maxServices) { + return false; + } + + return true; +}; + +/** + * تسجيل مشاهدة للمتجر + */ +storeSettingsSchema.methods.trackView = async function() { + this.extendedStats.totalViews += 1; + await this.save(); +}; + +/** + * تسجيل عملية بيع + */ +storeSettingsSchema.methods.trackSale = async function(amount) { + this.extendedStats.totalSales += amount; + this.extendedStats.totalOrders += 1; + + // تحديث متوسط قيمة الطلب + this.extendedStats.averageOrderValue = this.extendedStats.totalSales / this.extendedStats.totalOrders; + + // تحديث نسبة التحويل (يمكن تحديثها لاحقاً مع عدد الزوار) + if (this.extendedStats.totalUniqueVisitors > 0) { + this.extendedStats.conversionRate = (this.extendedStats.totalOrders / this.extendedStats.totalUniqueVisitors) * 100; + } + + await this.save(); +}; + +/** + * التحقق من صحة كوبون الخصم + */ +storeSettingsSchema.methods.validateCoupon = async function(code, cartTotal) { + const coupon = this.storeCoupons?.find(c => c.code === code.toUpperCase() && c.isActive); + + if (!coupon) return { valid: false, message: 'Invalid coupon code' }; + + const now = new Date(); + if (coupon.validUntil && now > coupon.validUntil) { + return { valid: false, message: 'Coupon has expired' }; + } + + if (coupon.validFrom && now < coupon.validFrom) { + return { valid: false, message: 'Coupon not yet active' }; + } + + if (coupon.usageLimit && coupon.usedCount >= coupon.usageLimit) { + return { valid: false, message: 'Coupon usage limit reached' }; + } + + if (cartTotal < coupon.minPurchase) { + return { valid: false, message: `Minimum purchase of ${this.currencySymbol}${coupon.minPurchase} required` }; + } + + let discount = 0; + if (coupon.discountType === 'percentage') { + discount = (cartTotal * coupon.discount) / 100; + if (coupon.maxDiscount && discount > coupon.maxDiscount) { + discount = coupon.maxDiscount; + } + } else { + discount = Math.min(coupon.discount, cartTotal); + } + + return { + valid: true, + discount: discount, + finalTotal: cartTotal - discount, + coupon: coupon + }; +}; + +const StoreSettings = mongoose.model('StoreSettings', storeSettingsSchema); + + +/** + * نموذج قوالب المتجر - يدعم القوالب المخصصة والافتراضية + * @version 2.0.0 + */ + +const storeThemeSchema = new mongoose.Schema({ + userId: { + type: mongoose.Schema.Types.ObjectId, + ref: 'User', + required: true, + unique: true, + index: true + }, + + // معلومات القالب الأساسية + name: { + type: String, + default: 'Default Theme', + trim: true, + maxlength: 100 + }, + isActive: { + type: Boolean, + default: true, + index: true + }, + version: { + type: String, + default: '1.0.0', + match: /^\d+\.\d+\.\d+$/ + }, + + // تصميم القالب (Layout) + layout: { + type: String, + enum: ['full-width', 'boxed', 'fluid', 'dashboard', 'minimal'], + default: 'full-width' + }, + + // قوالب HTML مخصصة + customTemplates: { + header: { type: String, default: '', maxlength: 50000 }, + footer: { type: String, default: '', maxlength: 50000 }, + sidebar: { type: String, default: '', maxlength: 50000 }, + productCard: { type: String, default: '', maxlength: 20000 }, + categoryCard: { type: String, default: '', maxlength: 20000 } + }, + + // ملف القالب المرفوع (ZIP) + uploadedTheme: { + filename: { type: String }, + originalName: { type: String }, + fileUrl: { type: String }, + fileSize: { type: Number }, + fileHash: { type: String }, // للتأكد من عدم تكرار الرفع + mimeType: { type: String }, + uploadedAt: { type: Date, default: Date.now }, + extractedFiles: { + htmlFiles: [{ name: String, size: Number }], + cssFiles: [{ name: String, size: Number }], + jsFiles: [{ name: String, size: Number }], + imageFiles: [{ name: String, size: Number, url: String }] + } + }, + + // إعدادات القالب + settings: { + containerWidth: { + type: String, + default: '1280px', + match: /^\d+(px|rem|em|%|vw|vh)$/ + }, + containerPadding: { + type: String, + default: '20px' + }, + showBreadcrumb: { + type: Boolean, + default: true + }, + stickyHeader: { + type: Boolean, + default: false + }, + backToTop: { + type: Boolean, + default: true + }, + showSearchBar: { + type: Boolean, + default: true + }, + showCategories: { + type: Boolean, + default: true + }, + productsPerRow: { + type: Number, + enum: [2, 3, 4, 6], + default: 4 + }, + productsPerPage: { + type: Number, + min: 6, + max: 48, + default: 12 + }, + enableLazyLoad: { + type: Boolean, + default: true + }, + enableAnimations: { + type: Boolean, + default: true + } + }, + + // ألوان القالب (CSS Variables) + colors: { + primary: { type: String, default: '#3b82f6', match: /^#[0-9A-Fa-f]{6}$/ }, + secondary: { type: String, default: '#8b5cf6', match: /^#[0-9A-Fa-f]{6}$/ }, + accent: { type: String, default: '#f59e0b', match: /^#[0-9A-Fa-f]{6}$/ }, + background: { type: String, default: '#ffffff', match: /^#[0-9A-Fa-f]{6}$/ }, + text: { type: String, default: '#1f2937', match: /^#[0-9A-Fa-f]{6}$/ }, + textLight: { type: String, default: '#6b7280', match: /^#[0-9A-Fa-f]{6}$/ }, + border: { type: String, default: '#e5e7eb', match: /^#[0-9A-Fa-f]{6}$/ }, + success: { type: String, default: '#10b981', match: /^#[0-9A-Fa-f]{6}$/ }, + error: { type: String, default: '#ef4444', match: /^#[0-9A-Fa-f]{6}$/ }, + warning: { type: String, default: '#f59e0b', match: /^#[0-9A-Fa-f]{6}$/ } + }, + + // خطوط القالب + typography: { + fontFamily: { + type: String, + default: 'Inter, sans-serif', + enum: ['Inter, sans-serif', 'Poppins, sans-serif', 'Roboto, sans-serif', 'Open Sans, sans-serif', 'Playfair Display, serif'] + }, + headingFont: { + type: String, + default: 'Inter, sans-serif' + }, + baseFontSize: { + type: String, + default: '16px', + match: /^\d+(px|rem)$/ + }, + enableGoogleFonts: { + type: Boolean, + default: true + } + }, + + // CSS/JS المخصص + customAssets: { + css: { type: String, default: '', maxlength: 100000 }, + js: { type: String, default: '', maxlength: 100000 }, + headHtml: { type: String, default: '', maxlength: 10000 }, + bodyHtml: { type: String, default: '', maxlength: 10000 } + }, + + // تحسين محركات البحث (SEO للقالب نفسه) + seo: { + metaTitle: { type: String, maxlength: 70 }, + metaDescription: { type: String, maxlength: 160 }, + metaKeywords: { type: String, maxlength: 200 }, + ogImage: { type: String }, + twitterCard: { type: String, default: 'summary_large_image' }, + canonicalUrl: { type: String }, + structuredData: { type: mongoose.Schema.Types.Mixed, default: {} } + }, + + // إحصائيات استخدام القالب + stats: { + views: { type: Number, default: 0 }, + lastUsed: { type: Date }, + templateChanges: { type: Number, default: 0 }, + lastChangeAt: { type: Date } + }, + + // حالة القالب + isDeleted: { + type: Boolean, + default: false, + index: true + }, + deletedAt: { + type: Date + }, + + createdAt: { type: Date, default: Date.now, immutable: true }, + updatedAt: { type: Date, default: Date.now } +}, { + timestamps: true, + toJSON: { virtuals: true }, + toObject: { virtuals: true } +}); + +// ============================================ +// Indexes لتحسين الأداء +// ============================================ +storeThemeSchema.index({ userId: 1, isActive: 1 }); +storeThemeSchema.index({ 'stats.views': -1 }); +storeThemeSchema.index({ updatedAt: -1 }); +storeThemeSchema.index({ isDeleted: 1 }); + +// ============================================ +// Virtuals +// ============================================ +storeThemeSchema.virtual('isCustomTheme').get(function() { + return !!this.uploadedTheme?.fileUrl; +}); + +storeThemeSchema.virtual('themeUrl').get(function() { + const baseUrl = process.env.BASE_URL || 'https://mgzon-server.hf.space'; + return `${baseUrl}/api/store/theme/${this.userId}`; +}); + +// ============================================ +// Middleware: قبل الحفظ +// ============================================ +storeThemeSchema.pre('save', function(next) { + this.updatedAt = Date.now(); + + // تنظيف HTML من الأكواد الضارة + if (this.customTemplates.header) { + this.customTemplates.header = sanitizeHtml(this.customTemplates.header); + } + if (this.customTemplates.footer) { + this.customTemplates.footer = sanitizeHtml(this.customTemplates.footer); + } + + // توليد hash للملف إذا لم يكن موجوداً + if (this.uploadedTheme && this.uploadedTheme.fileUrl && !this.uploadedTheme.fileHash) { + this.uploadedTheme.fileHash = createHash('md5') + .update(this.uploadedTheme.fileUrl + this.userId) + .digest('hex'); + } + + next(); +}); + +// ============================================ +// Static Methods +// ============================================ + +/** + * جلب القالب النشط لمستخدم معين + * @param {string} userId - معرف المستخدم + * @returns {Promise} - القالب النشط + */ +storeThemeSchema.statics.getActiveTheme = async function(userId) { + let theme = await this.findOne({ userId, isActive: true, isDeleted: false }); + + if (!theme) { + // إنشاء قالب افتراضي + theme = new this({ userId }); + await theme.save(); + } + + // تحديث إحصائيات الاستخدام + theme.stats.views += 1; + theme.stats.lastUsed = new Date(); + await theme.save(); + + return theme; +}; + +/** + * نسخ قالب من مستخدم إلى آخر + * @param {string} sourceUserId - مصدر القالب + * @param {string} targetUserId - المستخدم المستهدف + * @returns {Promise} - القالب الجديد + */ +storeThemeSchema.statics.cloneTheme = async function(sourceUserId, targetUserId) { + const sourceTheme = await this.findOne({ userId: sourceUserId, isActive: true }); + if (!sourceTheme) { + throw new Error('Source theme not found'); + } + + const themeData = sourceTheme.toObject(); + delete themeData._id; + delete themeData.userId; + delete themeData.createdAt; + delete themeData.updatedAt; + delete themeData.stats; + + const newTheme = new this({ + ...themeData, + userId: targetUserId, + name: `${sourceTheme.name} (Copy)`, + stats: { views: 0, templateChanges: 0 } + }); + + await newTheme.save(); + return newTheme; +}; + +/** + * إعادة تعيين القالب إلى الإعدادات الافتراضية + * @param {string} userId - معرف المستخدم + * @returns {Promise} - القالب المعاد تعيينه + */ +storeThemeSchema.statics.resetToDefault = async function(userId) { + await this.deleteOne({ userId }); + return this.getActiveTheme(userId); +}; + +// ============================================ +// Instance Methods +// ============================================ + +/** + * تطبيق القالب على HTML المحتوى + * @param {string} content - المحتوى الأصلي + * @returns {string} - المحتوى بعد تطبيق القالب + */ +storeThemeSchema.methods.applyToContent = function(content) { + let result = content; + + // تطبيق الهيدر المخصص + if (this.customTemplates.header) { + result = this.customTemplates.header + result; + } + + // تطبيق الفوتر المخصص + if (this.customTemplates.footer) { + result = result + this.customTemplates.footer; + } + + // إضافة CSS المخصص + if (this.customAssets.css) { + const cssTag = ``; + result = result.replace('', `${cssTag}`); + } + + // إضافة JS المخصص + if (this.customAssets.js) { + const jsTag = `