Mark-Lasfar commited on
Commit
a4e0b05
·
1 Parent(s): 8086e12

feat: add full design customization system with backend APIs and floating controls

Browse files
Files changed (1) hide show
  1. server.js +721 -161
server.js CHANGED
@@ -262,7 +262,20 @@ const excludedPaths = [
262
  '/api/store/products',
263
  '/api/store/:username/products',
264
  '/api/store/products/:productId',
265
- '/api/store/checkout',
 
 
 
 
 
 
 
 
 
 
 
 
 
266
  '/api/store/orders/buyer',
267
  '/api/store/orders/seller',
268
  '/api/store/orders/:orderId/status',
@@ -1397,6 +1410,8 @@ notificationSchema.index({ userId: 1, createdAt: -1 });
1397
  notificationSchema.index({ userId: 1, read: 1 });
1398
 
1399
  const Notification = mongoose.model('Notification', notificationSchema);
 
 
1400
  const followSchema = new mongoose.Schema({
1401
  followerId: {
1402
  type: mongoose.Schema.Types.ObjectId,
@@ -1476,8 +1491,10 @@ const orderSchema = new mongoose.Schema({
1476
  productId: { type: mongoose.Schema.Types.ObjectId, ref: 'Product' },
1477
  productType: { type: String },
1478
  title: { type: String },
 
1479
  price: { type: Number },
1480
- fileUrl: { type: String } // للتحميل بعد الدفع (للمنتجات الرقمية)
 
1481
  }],
1482
 
1483
  trackingNumber: { type: String }, // للشحن
@@ -2081,16 +2098,58 @@ const StoreFollow = mongoose.model('StoreFollow', storeFollowSchema);
2081
 
2082
 
2083
 
2084
- // 5. نموذج عربة التسوق المؤقتة (Cart - تخزين في MongoDB كـ backup)
2085
  const cartSchema = new mongoose.Schema({
2086
  userId: { type: mongoose.Schema.Types.ObjectId, ref: 'User', required: true, unique: true },
2087
- items: [{
2088
- productId: { type: mongoose.Schema.Types.ObjectId, ref: 'Product' },
2089
- quantity: { type: Number, default: 1 }
2090
- }],
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2091
  updatedAt: { type: Date, default: Date.now }
2092
  });
2093
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2094
  const Cart = mongoose.model('Cart', cartSchema);
2095
 
2096
  // Schema for layout presets (if not exists, create model)
@@ -18115,135 +18174,223 @@ app.get('/api/users/:userId/subscription-status', async (req, res) => {
18115
  });
18116
 
18117
  // ========== 3. الطلبات ==========
18118
-
18119
- // POST /api/store/checkout - إنشاء طلب جديد
18120
- app.post('/api/store/checkout', authenticateToken, async (req, res) => {
 
18121
  try {
18122
- const { items, subtotal, totalAmount, paymentMethod, paymentDetails, buyerNotes, sellerId } = req.body;
 
18123
 
18124
- if (!items || items.length === 0) {
 
 
 
 
18125
  return res.status(400).json({ error: 'Cart is empty' });
18126
  }
18127
 
18128
- // التحقق من أن المنتجات لا تزال متاحة
18129
- for (const item of items) {
18130
- const product = await Product.findById(item.productId);
18131
- if (!product || !product.isActive) {
18132
- return res.status(400).json({ error: `Product "${item.title}" is no longer available` });
18133
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
18134
  }
18135
 
18136
  // جلب بيانات المشتري والبائع
18137
  const buyer = await User.findById(req.user.userId);
18138
- const seller = await User.findById(sellerId);
18139
- const storeSettings = await StoreSettings.findOne({ userId: sellerId });
18140
 
18141
  if (!buyer || !seller) {
18142
  return res.status(404).json({ error: 'User not found' });
18143
  }
18144
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
18145
  const order = new Order({
 
18146
  buyerId: req.user.userId,
18147
- sellerId,
18148
- items,
18149
- subtotal,
18150
- totalAmount,
18151
- paymentMethod,
18152
- paymentDetails,
 
 
 
 
 
 
 
 
18153
  buyerNotes: buyerNotes || '',
18154
- status: 'pending'
18155
  });
18156
 
18157
  await order.save();
18158
 
18159
  // ============================================
18160
- // 📧 1. إرسال إيميل تأكيد للمشتري
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
18161
  // ============================================
18162
  const buyerEmailHtml = `
18163
  <!DOCTYPE html>
18164
  <html dir="ltr">
18165
  <head>
18166
  <meta charset="UTF-8">
 
 
18167
  <style>
18168
- body { font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; line-height: 1.6; color: #333; }
18169
  .container { max-width: 600px; margin: 0 auto; padding: 20px; }
18170
  .header { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; padding: 30px; text-align: center; border-radius: 10px 10px 0 0; }
18171
- .content { background: #f9fafb; padding: 30px; border-radius: 0 0 10px 10px; }
18172
- .order-details { background: white; padding: 20px; border-radius: 10px; margin: 20px 0; border: 1px solid #e5e7eb; }
18173
  .product-item { padding: 10px 0; border-bottom: 1px solid #e5e7eb; display: flex; justify-content: space-between; }
18174
  .total { font-size: 18px; font-weight: bold; margin-top: 20px; padding-top: 20px; border-top: 2px solid #e5e7eb; }
18175
  .button { display: inline-block; background: #667eea; color: white; padding: 12px 24px; text-decoration: none; border-radius: 8px; margin-top: 20px; }
18176
  .footer { text-align: center; padding: 20px; font-size: 12px; color: #6b7280; }
 
18177
  </style>
18178
  </head>
18179
  <body>
18180
  <div class="container">
18181
  <div class="header">
18182
- <h1>🛒 Order Confirmation</h1>
18183
  <p>Order #${order.orderNumber}</p>
18184
  </div>
18185
  <div class="content">
18186
- <h2>Thank you for your order, ${buyer.username}! 🎉</h2>
18187
- <p>Your order has been received and is now being processed.</p>
18188
 
18189
  <div class="order-details">
18190
- <h3>Order Details</h3>
18191
- <p><strong>Order Number:</strong> ${order.orderNumber}</p>
18192
  <p><strong>Date:</strong> ${new Date().toLocaleString()}</p>
18193
- <p><strong>Payment Method:</strong> ${paymentMethod === 'vodafone' ? 'Vodafone Cash' : paymentMethod === 'instapay' ? 'InstaPay' : paymentMethod === 'paypal' ? 'PayPal' : paymentMethod === 'stripe' ? 'Credit Card' : 'Bank Transfer'}</p>
 
18194
 
18195
- <h3 style="margin-top: 20px;">Items</h3>
18196
- ${items.map(item => `
18197
  <div class="product-item">
18198
- <span>${item.title} x1</span>
18199
- <span>${item.price} ${storeSettings?.currencySymbol || '$'}</span>
18200
  </div>
18201
  `).join('')}
18202
 
18203
  <div class="product-item" style="font-weight: bold;">
18204
  <span>Subtotal</span>
18205
- <span>${subtotal} ${storeSettings?.currencySymbol || '$'}</span>
18206
  </div>
18207
- ${totalAmount !== subtotal ? `
18208
- <div class="product-item" style="color: #10b981;">
18209
- <span>Discount</span>
18210
- <span>-${(subtotal - totalAmount).toFixed(2)} ${storeSettings?.currencySymbol || '$'}</span>
18211
- </div>
18212
- ` : ''}
18213
  <div class="total">
18214
- <span>Total Amount</span>
18215
- <span style="font-size: 24px; color: #667eea;">${totalAmount} ${storeSettings?.currencySymbol || '$'}</span>
18216
  </div>
18217
  </div>
18218
 
18219
  <div class="payment-info">
18220
  <h3>💰 Payment Instructions</h3>
18221
- ${paymentMethod === 'vodafone' ? `
18222
- <p>Please send the amount to this Vodafone Cash number:</p>
18223
- <p style="font-size: 24px; font-weight: bold; text-align: center; background: #f3f4f6; padding: 10px; border-radius: 8px;">
18224
- ${paymentDetails?.phone || 'Waiting for seller to provide'}
18225
- </p>
18226
- <p>After payment, the seller will process your order and you'll receive download links.</p>
18227
- ` : paymentMethod === 'instapay' ? `
18228
- <p>Please send the amount to this InstaPay account:</p>
18229
- <p style="font-size: 18px; font-weight: bold; text-align: center; background: #f3f4f6; padding: 10px; border-radius: 8px;">
18230
- ${paymentDetails?.phone || 'Waiting for seller to provide'}
18231
- </p>
18232
- ` : paymentMethod === 'bank' ? `
18233
- <p>Please transfer the amount to this bank account:</p>
18234
- <p style="background: #f3f4f6; padding: 10px; border-radius: 8px;">
18235
- <strong>Bank:</strong> ${paymentDetails?.bankName || 'N/A'}<br>
18236
- <strong>Account Name:</strong> ${paymentDetails?.accountName || 'N/A'}<br>
18237
- <strong>Account Number:</strong> ${paymentDetails?.accountNumber || 'N/A'}
18238
- </p>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
18239
  ` : `
18240
- <p>You will be redirected to complete payment securely.</p>
 
 
18241
  `}
18242
  </div>
18243
 
18244
- <a href="${process.env.BASE_URL}/store/orders/${order._id}" class="button">📦 View Order Status</a>
 
 
18245
 
18246
- <p style="margin-top: 20px; font-size: 14px; color: #6b7280;">
 
 
 
 
 
 
 
 
18247
  If you have any questions, please contact the seller directly.
18248
  </p>
18249
  </div>
@@ -18261,27 +18408,29 @@ app.post('/api/store/checkout', authenticateToken, async (req, res) => {
18261
  buyer.email,
18262
  `✅ Order Confirmation #${order.orderNumber}`,
18263
  buyerEmailHtml,
18264
- `Thank you for your order! Order #${order.orderNumber} has been confirmed. Total: ${totalAmount} ${storeSettings?.currencySymbol || '$'}`
18265
  );
18266
 
18267
  // ============================================
18268
- // 📧 2. إرسال إيميل للبائع (إشعار بطلب جديد)
18269
  // ============================================
18270
  const sellerEmailHtml = `
18271
  <!DOCTYPE html>
18272
  <html dir="ltr">
18273
  <head>
18274
  <meta charset="UTF-8">
 
 
18275
  <style>
18276
- body { font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; line-height: 1.6; color: #333; }
18277
  .container { max-width: 600px; margin: 0 auto; padding: 20px; }
18278
  .header { background: linear-gradient(135deg, #f59e0b 0%, #ef4444 100%); color: white; padding: 30px; text-align: center; border-radius: 10px 10px 0 0; }
18279
- .content { background: #f9fafb; padding: 30px; border-radius: 0 0 10px 10px; }
18280
- .order-details { background: white; padding: 20px; border-radius: 10px; margin: 20px 0; border: 1px solid #e5e7eb; }
18281
- .button { display: inline-block; background: #f59e0b; color: white; padding: 12px 24px; text-decoration: none; border-radius: 8px; margin-top: 20px; }
18282
- .action-buttons { display: flex; gap: 10px; margin-top: 20px; }
18283
- .btn-primary { background: #10b981; color: white; padding: 10px 20px; text-decoration: none; border-radius: 8px; display: inline-block; }
18284
- .btn-secondary { background: #6b7280; color: white; padding: 10px 20px; text-decoration: none; border-radius: 8px; display: inline-block; }
18285
  </style>
18286
  </head>
18287
  <body>
@@ -18292,30 +18441,32 @@ app.post('/api/store/checkout', authenticateToken, async (req, res) => {
18292
  </div>
18293
  <div class="content">
18294
  <h2>Congratulations, ${seller.profile?.nickname || seller.username}! 🎉</h2>
18295
- <p>You have received a new order from <strong>${buyer.username}</strong>.</p>
18296
 
18297
  <div class="order-details">
18298
- <h3>Order Details</h3>
18299
- <p><strong>Order Number:</strong> ${order.orderNumber}</p>
18300
  <p><strong>Customer:</strong> ${buyer.username} (${buyer.email})</p>
18301
  <p><strong>Date:</strong> ${new Date().toLocaleString()}</p>
18302
- <p><strong>Payment Method:</strong> ${paymentMethod === 'vodafone' ? 'Vodafone Cash' : paymentMethod === 'instapay' ? 'InstaPay' : paymentMethod === 'paypal' ? 'PayPal' : paymentMethod === 'stripe' ? 'Credit Card' : 'Bank Transfer'}</p>
18303
 
18304
- <h3 style="margin-top: 20px;">Items Ordered</h3>
18305
- ${items.map(item => `
18306
  <div class="product-item" style="padding: 10px 0; border-bottom: 1px solid #e5e7eb;">
18307
  <strong>${item.title}</strong><br>
18308
  Type: ${item.productType}<br>
18309
- Price: ${item.price} ${storeSettings?.currencySymbol || '$'}
 
18310
  </div>
18311
  `).join('')}
18312
 
18313
  <div class="total" style="margin-top: 20px; padding-top: 20px; border-top: 2px solid #e5e7eb;">
18314
- <strong>Total Amount:</strong> ${totalAmount} ${storeSettings?.currencySymbol || '$'}
 
18315
  </div>
18316
 
18317
  ${buyerNotes ? `
18318
- <div style="margin-top: 20px; padding: 10px; background: #fef3c7; border-radius: 8px;">
18319
  <strong>📝 Customer Notes:</strong><br>
18320
  ${buyerNotes}
18321
  </div>
@@ -18323,23 +18474,28 @@ app.post('/api/store/checkout', authenticateToken, async (req, res) => {
18323
  </div>
18324
 
18325
  <div class="action-buttons">
18326
- <a href="${process.env.BASE_URL}/store/orders/${order._id}" class="btn-primary">📦 View & Process Order</a>
18327
- <a href="${process.env.BASE_URL}/store/earnings" class="btn-secondary">💰 Earnings Dashboard</a>
18328
  </div>
18329
 
18330
- <div class="payment-info" style="margin-top: 20px; padding: 15px; background: #dbeafe; border-radius: 8px;">
18331
  <h3>💡 Next Steps</h3>
18332
  <ol style="margin: 0; padding-left: 20px;">
18333
- <li>Confirm payment receipt from the customer</li>
18334
- <li>Update order status to "Processing"</li>
18335
- <li>For digital products: Upload files or provide download links</li>
18336
- <li>Mark order as "Completed" when done</li>
 
18337
  </ol>
18338
  </div>
 
 
 
 
18339
  </div>
18340
  <div class="footer">
18341
  <p>© ${new Date().getFullYear()} MGZon. All rights reserved.</p>
18342
- <p>You're receiving this email because you have a store on MGZon.</p>
18343
  </div>
18344
  </div>
18345
  </body>
@@ -18351,22 +18507,22 @@ app.post('/api/store/checkout', authenticateToken, async (req, res) => {
18351
  seller.email,
18352
  `🛍️ New Order #${order.orderNumber} from ${buyer.username}`,
18353
  sellerEmailHtml,
18354
- `New order received! Order #${order.orderNumber} from ${buyer.username}. Total: ${totalAmount} ${storeSettings?.currencySymbol || '$'}`
18355
  );
18356
 
18357
  // ============================================
18358
- // 📱 3. إرسال إشعار عبر Socket.IO (في الوقت الفعلي)
18359
  // ============================================
18360
  const io = req.app.get('io');
18361
  if (io) {
18362
  // إشعار للبائع
18363
- io.to(`user_${sellerId}`).emit('new_order_notification', {
18364
  orderId: order._id,
18365
  orderNumber: order.orderNumber,
18366
- buyerName: buyer.username,
18367
- totalAmount,
18368
- currency: storeSettings?.currencySymbol || '$',
18369
- itemsCount: items.length,
18370
  timestamp: new Date()
18371
  });
18372
 
@@ -18375,64 +18531,61 @@ app.post('/api/store/checkout', authenticateToken, async (req, res) => {
18375
  orderId: order._id,
18376
  orderNumber: order.orderNumber,
18377
  status: 'pending',
 
18378
  timestamp: new Date()
18379
  });
18380
  }
18381
 
18382
  // ============================================
18383
- // 📝 4. إنشاء إشعار في قاعدة البيانات
18384
  // ============================================
18385
 
18386
  // إشعار للبائع
18387
- const sellerNotification = new Notification({
18388
- userId: sellerId,
18389
- type: 'new_order',
18390
- actorId: req.user.userId,
18391
- actorName: buyer.username,
18392
- content: `New order #${order.orderNumber} from ${buyer.username} - ${items.length} item(s) - Total: ${totalAmount} ${storeSettings?.currencySymbol || '$'}`,
18393
- targetId: `/store/orders/${order._id}`,
18394
- targetType: 'store',
18395
- read: false
18396
- });
18397
- await sellerNotification.save();
 
 
 
 
 
18398
 
18399
  // إشعار للمشتري
18400
- const buyerNotification = new Notification({
18401
- userId: req.user.userId,
18402
- type: 'order_status_update',
18403
- actorId: sellerId,
18404
- actorName: seller.profile?.nickname || seller.username,
18405
- content: `Your order #${order.orderNumber} has been created and is pending confirmation`,
18406
- targetId: `/store/orders/${order._id}`,
18407
- targetType: 'store',
18408
- read: false
18409
- });
18410
- await buyerNotification.save();
18411
-
18412
- // ============================================
18413
- // ✅ 5. تحديث سلة التسوق (حذف العناصر المشتراة)
18414
- // ============================================
18415
- await Cart.findOneAndUpdate(
18416
- { userId: req.user.userId },
18417
- { $set: { items: [] } } // تفريغ السلة
18418
- );
18419
-
18420
- // ============================================
18421
- // 📊 6. تحديث إحصائيات المنتجات (زيادة عدد المشاهدات)
18422
- // ============================================
18423
- for (const item of items) {
18424
- await Product.findByIdAndUpdate(item.productId, {
18425
- $inc: { salesCount: 1 }
18426
  });
 
 
 
18427
  }
18428
 
18429
  // ============================================
18430
- // 🎉 7. إرسال الرد
18431
  // ============================================
18432
- res.json({
18433
- success: true,
18434
- orderId: order._id,
18435
  orderNumber: order.orderNumber,
 
 
 
18436
  message: 'Order created successfully! Check your email for confirmation.'
18437
  });
18438
 
@@ -18442,6 +18595,32 @@ app.post('/api/store/checkout', authenticateToken, async (req, res) => {
18442
  }
18443
  });
18444
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
18445
  // GET /api/store/orders/buyer - جلب طلبات المستخدم (كمشتري)
18446
  app.get('/api/store/orders/buyer', authenticateToken, async (req, res) => {
18447
  try {
@@ -18497,37 +18676,418 @@ app.get('/api/store/earnings', authenticateToken, async (req, res) => {
18497
 
18498
  // ========== 5. عربة التسوق (Backup) ==========
18499
 
18500
- // GET /api/store/cart - جلب عربة التسوق
18501
- app.get('/api/store/cart', authenticateToken, async (req, res) => {
 
 
 
18502
  try {
18503
- let cart = await Cart.findOne({ userId: req.user.userId }).populate('items.productId');
18504
 
18505
  if (!cart) {
18506
- cart = { items: [] };
 
 
 
18507
  }
18508
 
18509
- res.json({ success: true, cart });
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
18510
  } catch (error) {
18511
  console.error('Error fetching cart:', error);
18512
  res.status(500).json({ error: 'Failed to fetch cart' });
18513
  }
18514
  });
18515
 
18516
- // POST /api/store/cart - حفظ عربة التسوق (Sync)
18517
- app.post('/api/store/cart', authenticateToken, async (req, res) => {
 
 
18518
  try {
18519
- const { items } = req.body;
 
 
 
 
 
 
 
 
 
18520
 
18521
- const cart = await Cart.findOneAndUpdate(
18522
- { userId: req.user.userId },
18523
- { items, updatedAt: Date.now() },
18524
- { upsert: true, new: true }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
18525
  );
18526
 
18527
- res.json({ success: true, cart });
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
18528
  } catch (error) {
18529
- console.error('Error saving cart:', error);
18530
- res.status(500).json({ error: 'Failed to save cart' });
18531
  }
18532
  });
18533
 
 
262
  '/api/store/products',
263
  '/api/store/:username/products',
264
  '/api/store/products/:productId',
265
+
266
+
267
+
268
+ '/api/cart',
269
+ '/api/cart/add',
270
+ '/api/cart/update',
271
+ '/api/cart/remove',
272
+ '/api/cart/clear-store',
273
+ '/api/cart/store/:storeId',
274
+ '/api/cart/clear-all',
275
+ '/api/cart/summary',
276
+ '/api/checkout/payment-info/:storeId',
277
+ '/api/checkout/:storeId',
278
+
279
  '/api/store/orders/buyer',
280
  '/api/store/orders/seller',
281
  '/api/store/orders/:orderId/status',
 
1410
  notificationSchema.index({ userId: 1, read: 1 });
1411
 
1412
  const Notification = mongoose.model('Notification', notificationSchema);
1413
+
1414
+
1415
  const followSchema = new mongoose.Schema({
1416
  followerId: {
1417
  type: mongoose.Schema.Types.ObjectId,
 
1491
  productId: { type: mongoose.Schema.Types.ObjectId, ref: 'Product' },
1492
  productType: { type: String },
1493
  title: { type: String },
1494
+ quantity: { type: Number, default: 1 },
1495
  price: { type: Number },
1496
+ fileUrl: { type: String },
1497
+ downloadCount: { type: Number, default: 0 }
1498
  }],
1499
 
1500
  trackingNumber: { type: String }, // للشحن
 
2098
 
2099
 
2100
 
2101
+ // 5. نموذج عربة التسوق
2102
  const cartSchema = new mongoose.Schema({
2103
  userId: { type: mongoose.Schema.Types.ObjectId, ref: 'User', required: true, unique: true },
2104
+ stores: {
2105
+ type: Map,
2106
+ of: new mongoose.Schema({
2107
+ storeId: { type: mongoose.Schema.Types.ObjectId, ref: 'User', required: true },
2108
+ storeName: { type: String, default: '' },
2109
+ storeLogo: { type: String, default: '' },
2110
+ items: [{
2111
+ productId: { type: mongoose.Schema.Types.ObjectId, ref: 'Product' },
2112
+ title: { type: String, required: true },
2113
+ price: { type: Number, required: true },
2114
+ quantity: { type: Number, default: 1, min: 1, max: 99 },
2115
+ image: { type: String, default: '/assets/img/default-product.png' },
2116
+ productType: { type: String, enum: ['digital', 'project', 'service'], default: 'digital' }
2117
+ }],
2118
+ subtotal: { type: Number, default: 0 },
2119
+ itemCount: { type: Number, default: 0 },
2120
+ createdAt: { type: Date, default: Date.now },
2121
+ updatedAt: { type: Date, default: Date.now }
2122
+ }),
2123
+ default: {}
2124
+ },
2125
+ totalItems: { type: Number, default: 0 },
2126
+ totalStores: { type: Number, default: 0 },
2127
+ createdAt: { type: Date, default: Date.now },
2128
  updatedAt: { type: Date, default: Date.now }
2129
  });
2130
 
2131
+ cartSchema.methods.calculateTotals = function() {
2132
+ let totalItems = 0;
2133
+ let totalStores = 0;
2134
+ for (let [storeId, storeData] of this.stores) {
2135
+ let storeTotal = 0;
2136
+ let storeItemCount = 0;
2137
+ for (const item of storeData.items) {
2138
+ storeTotal += item.price * item.quantity;
2139
+ storeItemCount += item.quantity;
2140
+ }
2141
+ storeData.subtotal = storeTotal;
2142
+ storeData.itemCount = storeItemCount;
2143
+ storeData.updatedAt = new Date();
2144
+ this.stores.set(storeId, storeData);
2145
+ totalItems += storeItemCount;
2146
+ totalStores++;
2147
+ }
2148
+ this.totalItems = totalItems;
2149
+ this.totalStores = totalStores;
2150
+ this.updatedAt = new Date();
2151
+ };
2152
+
2153
  const Cart = mongoose.model('Cart', cartSchema);
2154
 
2155
  // Schema for layout presets (if not exists, create model)
 
18174
  });
18175
 
18176
  // ========== 3. الطلبات ==========
18177
+ // ============================================
18178
+ // 8. POST /api/checkout/:storeId - إنشاء طلب لمتجر واحد (نسخة كاملة)
18179
+ // ============================================
18180
+ app.post('/api/checkout/:storeId', authenticateToken, async (req, res) => {
18181
  try {
18182
+ const { storeId } = req.params;
18183
+ const { buyerNotes, selectedPaymentMethod } = req.body;
18184
 
18185
+ // ============================================
18186
+ // 1. جلب السلة والتحقق
18187
+ // ============================================
18188
+ const cart = await Cart.findOne({ userId: req.user.userId });
18189
+ if (!cart) {
18190
  return res.status(400).json({ error: 'Cart is empty' });
18191
  }
18192
 
18193
+ const storeCart = cart.stores.get(storeId);
18194
+ if (!storeCart || storeCart.items.length === 0) {
18195
+ return res.status(400).json({ error: 'Store cart is empty' });
18196
+ }
18197
+
18198
+ // ============================================
18199
+ // 2. جلب بيانات المتجر والمستخدمين
18200
+ // ============================================
18201
+ const storeSettings = await StoreSettings.findOne({ userId: storeId });
18202
+ if (!storeSettings || !storeSettings.enabled) {
18203
+ return res.status(403).json({ error: 'Store is not active' });
18204
+ }
18205
+
18206
+ // جلب طريقة الدفع المختارة
18207
+ let paymentMethodData = null;
18208
+ if (selectedPaymentMethod) {
18209
+ paymentMethodData = storeSettings.paymentMethods.find(
18210
+ m => m.type === selectedPaymentMethod
18211
+ );
18212
+ } else if (storeSettings.paymentMethods && storeSettings.paymentMethods.length > 0) {
18213
+ paymentMethodData = storeSettings.paymentMethods[0];
18214
+ }
18215
+
18216
+ if (!paymentMethodData) {
18217
+ return res.status(400).json({ error: 'No payment method selected or available' });
18218
  }
18219
 
18220
  // جلب بيانات المشتري والبائع
18221
  const buyer = await User.findById(req.user.userId);
18222
+ const seller = await User.findById(storeId);
 
18223
 
18224
  if (!buyer || !seller) {
18225
  return res.status(404).json({ error: 'User not found' });
18226
  }
18227
 
18228
+ // ============================================
18229
+ // 3. التحقق من توفر المنتجات
18230
+ // ============================================
18231
+ for (const item of storeCart.items) {
18232
+ const product = await Product.findById(item.productId);
18233
+ if (!product || !product.isActive) {
18234
+ return res.status(400).json({
18235
+ error: `Product "${item.title}" is no longer available`
18236
+ });
18237
+ }
18238
+ }
18239
+
18240
+ // ============================================
18241
+ // 4. إنشاء الطلب
18242
+ // ============================================
18243
  const order = new Order({
18244
+ orderNumber: `ORD-${Date.now()}-${Math.floor(Math.random() * 10000)}`,
18245
  buyerId: req.user.userId,
18246
+ sellerId: storeId,
18247
+ items: storeCart.items.map(item => ({
18248
+ productId: item.productId,
18249
+ productType: item.productType,
18250
+ title: item.title,
18251
+ price: item.price,
18252
+ quantity: item.quantity
18253
+ })),
18254
+ subtotal: storeCart.subtotal,
18255
+ totalAmount: storeCart.subtotal,
18256
+ currency: storeSettings.currency || 'USD',
18257
+ status: 'pending',
18258
+ paymentMethod: paymentMethodData.type,
18259
+ paymentDetails: paymentMethodData.details || {},
18260
  buyerNotes: buyerNotes || '',
18261
+ createdAt: new Date()
18262
  });
18263
 
18264
  await order.save();
18265
 
18266
  // ============================================
18267
+ // 5. تحديث إحصائيات المنتجات (زيادة المبيعات)
18268
+ // ============================================
18269
+ for (const item of storeCart.items) {
18270
+ await Product.findByIdAndUpdate(item.productId, {
18271
+ $inc: { salesCount: item.quantity }
18272
+ });
18273
+ }
18274
+
18275
+ // ============================================
18276
+ // 6. مسح سلة هذا المتجر فقط
18277
+ // ============================================
18278
+ cart.stores.delete(storeId);
18279
+ await cart.calculateTotals();
18280
+ await cart.save();
18281
+
18282
+ // ============================================
18283
+ // 7. 📧 إرسال إيميل تأكيد للمشتري
18284
  // ============================================
18285
  const buyerEmailHtml = `
18286
  <!DOCTYPE html>
18287
  <html dir="ltr">
18288
  <head>
18289
  <meta charset="UTF-8">
18290
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
18291
+ <title>Order Confirmation</title>
18292
  <style>
18293
+ body { font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; line-height: 1.6; color: #333; margin: 0; padding: 0; background: #f4f4f4; }
18294
  .container { max-width: 600px; margin: 0 auto; padding: 20px; }
18295
  .header { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; padding: 30px; text-align: center; border-radius: 10px 10px 0 0; }
18296
+ .content { background: white; padding: 30px; border-radius: 0 0 10px 10px; box-shadow: 0 2px 10px rgba(0,0,0,0.1); }
18297
+ .order-details { background: #f9fafb; padding: 20px; border-radius: 10px; margin: 20px 0; border: 1px solid #e5e7eb; }
18298
  .product-item { padding: 10px 0; border-bottom: 1px solid #e5e7eb; display: flex; justify-content: space-between; }
18299
  .total { font-size: 18px; font-weight: bold; margin-top: 20px; padding-top: 20px; border-top: 2px solid #e5e7eb; }
18300
  .button { display: inline-block; background: #667eea; color: white; padding: 12px 24px; text-decoration: none; border-radius: 8px; margin-top: 20px; }
18301
  .footer { text-align: center; padding: 20px; font-size: 12px; color: #6b7280; }
18302
+ .status-badge { display: inline-block; background: #f59e0b; color: white; padding: 4px 12px; border-radius: 20px; font-size: 12px; }
18303
  </style>
18304
  </head>
18305
  <body>
18306
  <div class="container">
18307
  <div class="header">
18308
+ <h1>🛒 Order Confirmed!</h1>
18309
  <p>Order #${order.orderNumber}</p>
18310
  </div>
18311
  <div class="content">
18312
+ <h2>Thank you for your order, ${buyer.profile?.nickname || buyer.username}! 🎉</h2>
18313
+ <p>Your order has been received and is now being processed by <strong>${storeSettings.storeName || seller.profile?.nickname || seller.username}</strong>.</p>
18314
 
18315
  <div class="order-details">
18316
+ <h3>📋 Order Details</h3>
18317
+ <p><strong>Order Number:</strong> <span style="font-family: monospace;">${order.orderNumber}</span></p>
18318
  <p><strong>Date:</strong> ${new Date().toLocaleString()}</p>
18319
+ <p><strong>Status:</strong> <span class="status-badge">Pending Payment</span></p>
18320
+ <p><strong>Payment Method:</strong> ${paymentMethodData.type === 'vodafone' ? '📱 Vodafone Cash' : paymentMethodData.type === 'instapay' ? '🏦 InstaPay' : paymentMethodData.type === 'paypal' ? '💰 PayPal' : paymentMethodData.type === 'bank' ? '🏛️ Bank Transfer' : paymentMethodData.type}</p>
18321
 
18322
+ <h3 style="margin-top: 20px;">🛍️ Items Ordered</h3>
18323
+ ${storeCart.items.map(item => `
18324
  <div class="product-item">
18325
+ <span>${item.title} × ${item.quantity}</span>
18326
+ <span><strong>${storeSettings.currencySymbol || '$'}${(item.price * item.quantity).toFixed(2)}</strong></span>
18327
  </div>
18328
  `).join('')}
18329
 
18330
  <div class="product-item" style="font-weight: bold;">
18331
  <span>Subtotal</span>
18332
+ <span>${storeSettings.currencySymbol || '$'}${storeCart.subtotal.toFixed(2)}</span>
18333
  </div>
 
 
 
 
 
 
18334
  <div class="total">
18335
+ <span style="font-size: 20px;">Total Amount</span>
18336
+ <span style="font-size: 28px; color: #667eea; font-weight: bold;">${storeSettings.currencySymbol || '$'}${storeCart.subtotal.toFixed(2)}</span>
18337
  </div>
18338
  </div>
18339
 
18340
  <div class="payment-info">
18341
  <h3>💰 Payment Instructions</h3>
18342
+ ${paymentMethodData.type === 'vodafone' ? `
18343
+ <div style="background: #e0f2fe; padding: 15px; border-radius: 10px;">
18344
+ <p style="margin: 0 0 10px 0;">📱 Send the amount to this <strong>Vodafone Cash</strong> number:</p>
18345
+ <p style="font-size: 28px; font-weight: bold; text-align: center; background: white; padding: 10px; border-radius: 8px; font-family: monospace;">
18346
+ ${paymentMethodData.details?.phone || 'Not provided'}
18347
+ </p>
18348
+ <p style="margin: 10px 0 0 0; font-size: 12px; color: #666;">After payment, the seller will confirm and you'll receive access to your purchase.</p>
18349
+ </div>
18350
+ ` : paymentMethodData.type === 'instapay' ? `
18351
+ <div style="background: #d1fae5; padding: 15px; border-radius: 10px;">
18352
+ <p style="margin: 0 0 10px 0;">🏦 Send the amount to this <strong>InstaPay</strong> account:</p>
18353
+ <p style="font-size: 24px; font-weight: bold; text-align: center; background: white; padding: 10px; border-radius: 8px; font-family: monospace;">
18354
+ ${paymentMethodData.details?.phone || 'Not provided'}
18355
+ </p>
18356
+ </div>
18357
+ ` : paymentMethodData.type === 'paypal' ? `
18358
+ <div style="background: #e0e7ff; padding: 15px; border-radius: 10px;">
18359
+ <p style="margin: 0 0 10px 0;">💰 Send payment to this <strong>PayPal</strong> email:</p>
18360
+ <p style="font-size: 18px; font-weight: bold; text-align: center; background: white; padding: 10px; border-radius: 8px;">
18361
+ ${paymentMethodData.details?.email || 'Not provided'}
18362
+ </p>
18363
+ </div>
18364
+ ` : paymentMethodData.type === 'bank' ? `
18365
+ <div style="background: #fef3c7; padding: 15px; border-radius: 10px;">
18366
+ <p style="margin: 0 0 10px 0;">🏛️ Transfer the amount to this <strong>Bank Account</strong>:</p>
18367
+ <table style="width: 100%; background: white; padding: 10px; border-radius: 8px;">
18368
+ <tr><td><strong>Bank:</strong></td><td>${paymentMethodData.details?.bankName || 'N/A'}</td></tr>
18369
+ <tr><td><strong>Account Name:</strong></td><td>${paymentMethodData.details?.accountName || 'N/A'}</td></tr>
18370
+ <tr><td><strong>Account Number:</strong></td><td>${paymentMethodData.details?.accountNumber || 'N/A'}</td></tr>
18371
+ ${paymentMethodData.details?.iban ? `<tr><td><strong>IBAN:</strong></td><td>${paymentMethodData.details.iban}</td></tr>` : ''}
18372
+ </table>
18373
+ </div>
18374
  ` : `
18375
+ <div style="background: #e5e7eb; padding: 15px; border-radius: 10px;">
18376
+ <p>Please complete the payment using your selected method. The seller will be notified.</p>
18377
+ </div>
18378
  `}
18379
  </div>
18380
 
18381
+ <div style="text-align: center;">
18382
+ <a href="${process.env.BASE_URL || 'https://mgzon.com'}/store/orders/${order._id}" class="button">📦 Track Your Order</a>
18383
+ </div>
18384
 
18385
+ <p style="margin-top: 20px; font-size: 14px; color: #6b7280; text-align: center;">
18386
+ 💡 <strong>What's next?</strong><br>
18387
+ 1. Complete the payment using the instructions above<br>
18388
+ 2. The seller will confirm your payment<br>
18389
+ 3. You'll receive download links or delivery confirmation<br>
18390
+ 4. You can track your order status anytime
18391
+ </p>
18392
+
18393
+ <p style="margin-top: 20px; font-size: 12px; color: #9ca3af; text-align: center;">
18394
  If you have any questions, please contact the seller directly.
18395
  </p>
18396
  </div>
 
18408
  buyer.email,
18409
  `✅ Order Confirmation #${order.orderNumber}`,
18410
  buyerEmailHtml,
18411
+ `Thank you for your order! Order #${order.orderNumber} has been confirmed. Total: ${storeSettings.currencySymbol || '$'}${storeCart.subtotal.toFixed(2)}`
18412
  );
18413
 
18414
  // ============================================
18415
+ // 8. 📧 إرسال إيميل للبائع (إشعار بطلب جديد)
18416
  // ============================================
18417
  const sellerEmailHtml = `
18418
  <!DOCTYPE html>
18419
  <html dir="ltr">
18420
  <head>
18421
  <meta charset="UTF-8">
18422
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
18423
+ <title>New Order Received</title>
18424
  <style>
18425
+ body { font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; line-height: 1.6; color: #333; margin: 0; padding: 0; background: #f4f4f4; }
18426
  .container { max-width: 600px; margin: 0 auto; padding: 20px; }
18427
  .header { background: linear-gradient(135deg, #f59e0b 0%, #ef4444 100%); color: white; padding: 30px; text-align: center; border-radius: 10px 10px 0 0; }
18428
+ .content { background: white; padding: 30px; border-radius: 0 0 10px 10px; box-shadow: 0 2px 10px rgba(0,0,0,0.1); }
18429
+ .order-details { background: #f9fafb; padding: 20px; border-radius: 10px; margin: 20px 0; border: 1px solid #e5e7eb; }
18430
+ .action-buttons { display: flex; gap: 10px; margin-top: 20px; flex-wrap: wrap; }
18431
+ .btn-primary { background: #10b981; color: white; padding: 12px 24px; text-decoration: none; border-radius: 8px; display: inline-block; }
18432
+ .btn-secondary { background: #6b7280; color: white; padding: 12px 24px; text-decoration: none; border-radius: 8px; display: inline-block; }
18433
+ .footer { text-align: center; padding: 20px; font-size: 12px; color: #6b7280; }
18434
  </style>
18435
  </head>
18436
  <body>
 
18441
  </div>
18442
  <div class="content">
18443
  <h2>Congratulations, ${seller.profile?.nickname || seller.username}! 🎉</h2>
18444
+ <p>You have received a new order from <strong>${buyer.profile?.nickname || buyer.username}</strong>.</p>
18445
 
18446
  <div class="order-details">
18447
+ <h3>📋 Order Details</h3>
18448
+ <p><strong>Order Number:</strong> <span style="font-family: monospace;">${order.orderNumber}</span></p>
18449
  <p><strong>Customer:</strong> ${buyer.username} (${buyer.email})</p>
18450
  <p><strong>Date:</strong> ${new Date().toLocaleString()}</p>
18451
+ <p><strong>Payment Method:</strong> ${paymentMethodData.type === 'vodafone' ? '📱 Vodafone Cash' : paymentMethodData.type === 'instapay' ? '🏦 InstaPay' : paymentMethodData.type === 'paypal' ? '💰 PayPal' : paymentMethodData.type === 'bank' ? '🏛️ Bank Transfer' : paymentMethodData.type}</p>
18452
 
18453
+ <h3 style="margin-top: 20px;">🛍️ Items Ordered</h3>
18454
+ ${storeCart.items.map(item => `
18455
  <div class="product-item" style="padding: 10px 0; border-bottom: 1px solid #e5e7eb;">
18456
  <strong>${item.title}</strong><br>
18457
  Type: ${item.productType}<br>
18458
+ Quantity: ${item.quantity}<br>
18459
+ Price: ${storeSettings.currencySymbol || '$'}${(item.price * item.quantity).toFixed(2)}
18460
  </div>
18461
  `).join('')}
18462
 
18463
  <div class="total" style="margin-top: 20px; padding-top: 20px; border-top: 2px solid #e5e7eb;">
18464
+ <strong>💰 Total Amount:</strong>
18465
+ <span style="font-size: 24px; color: #f59e0b;">${storeSettings.currencySymbol || '$'}${storeCart.subtotal.toFixed(2)}</span>
18466
  </div>
18467
 
18468
  ${buyerNotes ? `
18469
+ <div style="margin-top: 20px; padding: 15px; background: #fef3c7; border-radius: 8px;">
18470
  <strong>📝 Customer Notes:</strong><br>
18471
  ${buyerNotes}
18472
  </div>
 
18474
  </div>
18475
 
18476
  <div class="action-buttons">
18477
+ <a href="${process.env.BASE_URL || 'https://mgzon.com'}/store/orders/${order._id}" class="btn-primary">📦 View & Process Order</a>
18478
+ <a href="${process.env.BASE_URL || 'https://mgzon.com'}/store/earnings" class="btn-secondary">💰 Earnings Dashboard</a>
18479
  </div>
18480
 
18481
+ <div style="margin-top: 20px; padding: 15px; background: #dbeafe; border-radius: 8px;">
18482
  <h3>💡 Next Steps</h3>
18483
  <ol style="margin: 0; padding-left: 20px;">
18484
+ <li>✅ Confirm payment receipt from the customer</li>
18485
+ <li>📝 Update order status to "Processing"</li>
18486
+ <li>📎 For digital products: Upload files or provide download links</li>
18487
+ <li>🎉 Mark order as "Completed" when done</li>
18488
+ <li>⭐ Ask customer to leave a review</li>
18489
  </ol>
18490
  </div>
18491
+
18492
+ <p style="margin-top: 20px; font-size: 12px; color: #6b7280; text-align: center;">
18493
+ You're receiving this email because you have a store on MGZon.
18494
+ </p>
18495
  </div>
18496
  <div class="footer">
18497
  <p>© ${new Date().getFullYear()} MGZon. All rights reserved.</p>
18498
+ <p>This is an automated message, please do not reply.</p>
18499
  </div>
18500
  </div>
18501
  </body>
 
18507
  seller.email,
18508
  `🛍️ New Order #${order.orderNumber} from ${buyer.username}`,
18509
  sellerEmailHtml,
18510
+ `New order received! Order #${order.orderNumber} from ${buyer.username}. Total: ${storeSettings.currencySymbol || '$'}${storeCart.subtotal.toFixed(2)}`
18511
  );
18512
 
18513
  // ============================================
18514
+ // 9. 📱 إرسال إشعار عبر Socket.IO (في الوقت الفعلي)
18515
  // ============================================
18516
  const io = req.app.get('io');
18517
  if (io) {
18518
  // إشعار للبائع
18519
+ io.to(`user_${storeId}`).emit('new_order_notification', {
18520
  orderId: order._id,
18521
  orderNumber: order.orderNumber,
18522
+ buyerName: buyer.profile?.nickname || buyer.username,
18523
+ totalAmount: storeCart.subtotal,
18524
+ currency: storeSettings.currencySymbol || '$',
18525
+ itemsCount: storeCart.items.length,
18526
  timestamp: new Date()
18527
  });
18528
 
 
18531
  orderId: order._id,
18532
  orderNumber: order.orderNumber,
18533
  status: 'pending',
18534
+ storeName: storeSettings.storeName,
18535
  timestamp: new Date()
18536
  });
18537
  }
18538
 
18539
  // ============================================
18540
+ // 10. 📝 إنشاء إشعارات في قاعدة البيانات
18541
  // ============================================
18542
 
18543
  // إشعار للبائع
18544
+ try {
18545
+ const Notification = mongoose.model('Notification');
18546
+ const sellerNotification = new Notification({
18547
+ userId: storeId,
18548
+ type: 'new_order',
18549
+ actorId: req.user.userId,
18550
+ actorName: buyer.profile?.nickname || buyer.username,
18551
+ content: `🛍️ New order #${order.orderNumber} from ${buyer.profile?.nickname || buyer.username} - ${storeCart.items.length} item(s) - Total: ${storeSettings.currencySymbol || '$'}${storeCart.subtotal.toFixed(2)}`,
18552
+ targetId: `/store/orders/${order._id}`,
18553
+ targetType: 'store',
18554
+ read: false
18555
+ });
18556
+ await sellerNotification.save();
18557
+ } catch (e) {
18558
+ console.log('Notification model not found, skipping...');
18559
+ }
18560
 
18561
  // إشعار للمشتري
18562
+ try {
18563
+ const Notification = mongoose.model('Notification');
18564
+ const buyerNotification = new Notification({
18565
+ userId: req.user.userId,
18566
+ type: 'order_status_update',
18567
+ actorId: storeId,
18568
+ actorName: storeSettings.storeName || seller.profile?.nickname || seller.username,
18569
+ content: `✅ Your order #${order.orderNumber} has been created and is pending confirmation from the seller`,
18570
+ targetId: `/store/orders/${order._id}`,
18571
+ targetType: 'store',
18572
+ read: false
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
18573
  });
18574
+ await buyerNotification.save();
18575
+ } catch (e) {
18576
+ console.log('Notification model not found, skipping...');
18577
  }
18578
 
18579
  // ============================================
18580
+ // 11. 🎉 إرسال الرد النهائي
18581
  // ============================================
18582
+ res.json({
18583
+ success: true,
18584
+ orderId: order._id,
18585
  orderNumber: order.orderNumber,
18586
+ totalAmount: storeCart.subtotal,
18587
+ currencySymbol: storeSettings.currencySymbol || '$',
18588
+ paymentMethods: storeSettings.paymentMethods,
18589
  message: 'Order created successfully! Check your email for confirmation.'
18590
  });
18591
 
 
18595
  }
18596
  });
18597
 
18598
+ // ============================================
18599
+ // 9. GET /api/checkout/payment-info/:storeId - جلب معلومات الدفع للمتجر
18600
+ // ============================================
18601
+ app.get('/api/checkout/payment-info/:storeId', async (req, res) => {
18602
+ try {
18603
+ const { storeId } = req.params;
18604
+
18605
+ const storeSettings = await StoreSettings.findOne({ userId: storeId });
18606
+ if (!storeSettings) {
18607
+ return res.status(404).json({ error: 'Store not found' });
18608
+ }
18609
+
18610
+ res.json({
18611
+ success: true,
18612
+ paymentMethods: storeSettings.paymentMethods || [],
18613
+ currencySymbol: storeSettings.currencySymbol || '$',
18614
+ storeName: storeSettings.storeName,
18615
+ storeLogo: storeSettings.storeLogo
18616
+ });
18617
+
18618
+ } catch (error) {
18619
+ console.error('Error fetching payment info:', error);
18620
+ res.status(500).json({ error: 'Failed to fetch payment info' });
18621
+ }
18622
+ });
18623
+
18624
  // GET /api/store/orders/buyer - جلب طلبات المستخدم (كمشتري)
18625
  app.get('/api/store/orders/buyer', authenticateToken, async (req, res) => {
18626
  try {
 
18676
 
18677
  // ========== 5. عربة التسوق (Backup) ==========
18678
 
18679
+
18680
+ // ============================================
18681
+ // 1. GET /api/cart - جلب السلة كاملة
18682
+ // ============================================
18683
+ app.get('/api/cart', authenticateToken, async (req, res) => {
18684
  try {
18685
+ let cart = await Cart.findOne({ userId: req.user.userId });
18686
 
18687
  if (!cart) {
18688
+ return res.json({
18689
+ success: true,
18690
+ cart: { stores: [], totalItems: 0, totalStores: 0 }
18691
+ });
18692
  }
18693
 
18694
+ // تحويل الـ Map إلى Array للـ Frontend
18695
+ const storesArray = [];
18696
+ for (let [storeId, storeData] of cart.stores) {
18697
+ storesArray.push({
18698
+ storeId: storeId,
18699
+ storeName: storeData.storeName,
18700
+ storeLogo: storeData.storeLogo,
18701
+ items: storeData.items,
18702
+ subtotal: storeData.subtotal,
18703
+ itemCount: storeData.itemCount,
18704
+ updatedAt: storeData.updatedAt
18705
+ });
18706
+ }
18707
+
18708
+ res.json({
18709
+ success: true,
18710
+ cart: {
18711
+ stores: storesArray,
18712
+ totalItems: cart.totalItems,
18713
+ totalStores: cart.totalStores
18714
+ }
18715
+ });
18716
+
18717
  } catch (error) {
18718
  console.error('Error fetching cart:', error);
18719
  res.status(500).json({ error: 'Failed to fetch cart' });
18720
  }
18721
  });
18722
 
18723
+ // ============================================
18724
+ // 2. POST /api/cart/add - إضافة منتج للسلة
18725
+ // ============================================
18726
+ app.post('/api/cart/add', authenticateToken, async (req, res) => {
18727
  try {
18728
+ const {
18729
+ productId,
18730
+ storeId,
18731
+ storeName,
18732
+ title,
18733
+ price,
18734
+ image,
18735
+ productType,
18736
+ quantity = 1
18737
+ } = req.body;
18738
 
18739
+ // ✅ التحقق من البيانات
18740
+ if (!productId || !storeId || !title || !price) {
18741
+ return res.status(400).json({ error: 'Missing required fields' });
18742
+ }
18743
+
18744
+ if (quantity < 1 || quantity > 99) {
18745
+ return res.status(400).json({ error: 'Quantity must be between 1 and 99' });
18746
+ }
18747
+
18748
+ // ✅ جلب أو إنشاء السلة
18749
+ let cart = await Cart.findOne({ userId: req.user.userId });
18750
+
18751
+ if (!cart) {
18752
+ cart = new Cart({
18753
+ userId: req.user.userId,
18754
+ stores: new Map()
18755
+ });
18756
+ }
18757
+
18758
+ // ✅ الحصول على عربة هذا المتجر
18759
+ let storeCart = cart.stores.get(storeId);
18760
+
18761
+ if (!storeCart) {
18762
+ // إنشاء عربة جديدة لهذا المتجر
18763
+ storeCart = {
18764
+ storeId: storeId,
18765
+ storeName: storeName || 'Store',
18766
+ storeLogo: '',
18767
+ items: [],
18768
+ subtotal: 0,
18769
+ itemCount: 0,
18770
+ createdAt: new Date(),
18771
+ updatedAt: new Date()
18772
+ };
18773
+ }
18774
+
18775
+ // ✅ البحث عن المنتج الموجود
18776
+ const existingItemIndex = storeCart.items.findIndex(
18777
+ item => item.productId === productId
18778
  );
18779
 
18780
+ if (existingItemIndex !== -1) {
18781
+ // تحديث الكمية (حد أقصى 99)
18782
+ const newQuantity = storeCart.items[existingItemIndex].quantity + quantity;
18783
+ storeCart.items[existingItemIndex].quantity = Math.min(newQuantity, 99);
18784
+ } else {
18785
+ // إضافة منتج جديد
18786
+ storeCart.items.push({
18787
+ productId,
18788
+ title,
18789
+ price,
18790
+ quantity: Math.min(quantity, 99),
18791
+ image: image || '/assets/img/default-product.png',
18792
+ productType: productType || 'digital'
18793
+ });
18794
+ }
18795
+
18796
+ // ✅ حساب الإجماليات لهذا المتجر
18797
+ let subtotal = 0;
18798
+ let itemCount = 0;
18799
+ for (const item of storeCart.items) {
18800
+ subtotal += item.price * item.quantity;
18801
+ itemCount += item.quantity;
18802
+ }
18803
+ storeCart.subtotal = subtotal;
18804
+ storeCart.itemCount = itemCount;
18805
+ storeCart.updatedAt = new Date();
18806
+
18807
+ // ✅ حفظ في الـ Map
18808
+ cart.stores.set(storeId, storeCart);
18809
+
18810
+ // ✅ حساب إجماليات السلة الكلية
18811
+ await cart.calculateTotals();
18812
+
18813
+ await cart.save();
18814
+
18815
+ // ✅ إرجاع السلة المحدثة
18816
+ const updatedStoreCart = cart.stores.get(storeId);
18817
+
18818
+ res.json({
18819
+ success: true,
18820
+ message: 'Product added to cart',
18821
+ storeCart: {
18822
+ storeId: storeId,
18823
+ storeName: updatedStoreCart.storeName,
18824
+ items: updatedStoreCart.items,
18825
+ subtotal: updatedStoreCart.subtotal,
18826
+ itemCount: updatedStoreCart.itemCount
18827
+ },
18828
+ cartTotals: {
18829
+ totalItems: cart.totalItems,
18830
+ totalStores: cart.totalStores
18831
+ }
18832
+ });
18833
+
18834
+ } catch (error) {
18835
+ console.error('Error adding to cart:', error);
18836
+ res.status(500).json({ error: 'Failed to add to cart' });
18837
+ }
18838
+ });
18839
+
18840
+ // ============================================
18841
+ // 3. PUT /api/cart/update - تحديث كمية منتج
18842
+ // ============================================
18843
+ app.put('/api/cart/update', authenticateToken, async (req, res) => {
18844
+ try {
18845
+ const { storeId, productId, quantity } = req.body;
18846
+
18847
+ if (!storeId || !productId) {
18848
+ return res.status(400).json({ error: 'Missing required fields' });
18849
+ }
18850
+
18851
+ if (!quantity || quantity < 1 || quantity > 99) {
18852
+ return res.status(400).json({ error: 'Quantity must be between 1 and 99' });
18853
+ }
18854
+
18855
+ const cart = await Cart.findOne({ userId: req.user.userId });
18856
+ if (!cart) {
18857
+ return res.status(404).json({ error: 'Cart not found' });
18858
+ }
18859
+
18860
+ const storeCart = cart.stores.get(storeId);
18861
+ if (!storeCart) {
18862
+ return res.status(404).json({ error: 'Store not found in cart' });
18863
+ }
18864
+
18865
+ const itemIndex = storeCart.items.findIndex(item => item.productId === productId);
18866
+ if (itemIndex === -1) {
18867
+ return res.status(404).json({ error: 'Product not found in cart' });
18868
+ }
18869
+
18870
+ // تحديث الكمية
18871
+ storeCart.items[itemIndex].quantity = quantity;
18872
+
18873
+ // إعادة حساب الإجماليات
18874
+ let subtotal = 0;
18875
+ let itemCount = 0;
18876
+ for (const item of storeCart.items) {
18877
+ subtotal += item.price * item.quantity;
18878
+ itemCount += item.quantity;
18879
+ }
18880
+ storeCart.subtotal = subtotal;
18881
+ storeCart.itemCount = itemCount;
18882
+ storeCart.updatedAt = new Date();
18883
+
18884
+ cart.stores.set(storeId, storeCart);
18885
+ await cart.calculateTotals();
18886
+ await cart.save();
18887
+
18888
+ res.json({
18889
+ success: true,
18890
+ storeCart: {
18891
+ storeId: storeId,
18892
+ storeName: storeCart.storeName,
18893
+ items: storeCart.items,
18894
+ subtotal: storeCart.subtotal,
18895
+ itemCount: storeCart.itemCount
18896
+ },
18897
+ cartTotals: {
18898
+ totalItems: cart.totalItems,
18899
+ totalStores: cart.totalStores
18900
+ }
18901
+ });
18902
+
18903
+ } catch (error) {
18904
+ console.error('Error updating cart:', error);
18905
+ res.status(500).json({ error: 'Failed to update cart' });
18906
+ }
18907
+ });
18908
+
18909
+ // ============================================
18910
+ // 4. DELETE /api/cart/remove - حذف منتج من السلة
18911
+ // ============================================
18912
+ app.delete('/api/cart/remove', authenticateToken, async (req, res) => {
18913
+ try {
18914
+ const { storeId, productId } = req.body;
18915
+
18916
+ if (!storeId || !productId) {
18917
+ return res.status(400).json({ error: 'Missing required fields' });
18918
+ }
18919
+
18920
+ const cart = await Cart.findOne({ userId: req.user.userId });
18921
+ if (!cart) {
18922
+ return res.status(404).json({ error: 'Cart not found' });
18923
+ }
18924
+
18925
+ const storeCart = cart.stores.get(storeId);
18926
+ if (!storeCart) {
18927
+ return res.status(404).json({ error: 'Store not found in cart' });
18928
+ }
18929
+
18930
+ // حذف المنتج
18931
+ storeCart.items = storeCart.items.filter(item => item.productId !== productId);
18932
+
18933
+ if (storeCart.items.length === 0) {
18934
+ // إذا كانت السلة فارغة، احذف المتجر بالكامل
18935
+ cart.stores.delete(storeId);
18936
+ } else {
18937
+ // إعادة حساب الإجماليات
18938
+ let subtotal = 0;
18939
+ let itemCount = 0;
18940
+ for (const item of storeCart.items) {
18941
+ subtotal += item.price * item.quantity;
18942
+ itemCount += item.quantity;
18943
+ }
18944
+ storeCart.subtotal = subtotal;
18945
+ storeCart.itemCount = itemCount;
18946
+ storeCart.updatedAt = new Date();
18947
+ cart.stores.set(storeId, storeCart);
18948
+ }
18949
+
18950
+ await cart.calculateTotals();
18951
+ await cart.save();
18952
+
18953
+ res.json({
18954
+ success: true,
18955
+ message: 'Product removed from cart',
18956
+ cartTotals: {
18957
+ totalItems: cart.totalItems,
18958
+ totalStores: cart.totalStores
18959
+ }
18960
+ });
18961
+
18962
+ } catch (error) {
18963
+ console.error('Error removing from cart:', error);
18964
+ res.status(500).json({ error: 'Failed to remove from cart' });
18965
+ }
18966
+ });
18967
+
18968
+ // ============================================
18969
+ // 5. DELETE /api/cart/clear-store - تفريغ سلة متجر واحد
18970
+ // ============================================
18971
+ app.delete('/api/cart/clear-store', authenticateToken, async (req, res) => {
18972
+ try {
18973
+ const { storeId } = req.body;
18974
+
18975
+ if (!storeId) {
18976
+ return res.status(400).json({ error: 'Store ID is required' });
18977
+ }
18978
+
18979
+ const cart = await Cart.findOne({ userId: req.user.userId });
18980
+ if (!cart) {
18981
+ return res.status(404).json({ error: 'Cart not found' });
18982
+ }
18983
+
18984
+ cart.stores.delete(storeId);
18985
+ await cart.calculateTotals();
18986
+ await cart.save();
18987
+
18988
+ res.json({
18989
+ success: true,
18990
+ message: 'Store cart cleared',
18991
+ cartTotals: {
18992
+ totalItems: cart.totalItems,
18993
+ totalStores: cart.totalStores
18994
+ }
18995
+ });
18996
+
18997
+ } catch (error) {
18998
+ console.error('Error clearing store cart:', error);
18999
+ res.status(500).json({ error: 'Failed to clear store cart' });
19000
+ }
19001
+ });
19002
+
19003
+ // GET /api/cart/store/:storeId - جلب سلة متجر واحد
19004
+ app.get('/api/cart/store/:storeId', authenticateToken, async (req, res) => {
19005
+ try {
19006
+ const { storeId } = req.params;
19007
+ const cart = await Cart.findOne({ userId: req.user.userId });
19008
+
19009
+ if (!cart) {
19010
+ return res.json({ success: true, storeCart: null });
19011
+ }
19012
+
19013
+ const storeCart = cart.stores.get(storeId);
19014
+ if (!storeCart) {
19015
+ return res.json({ success: true, storeCart: null });
19016
+ }
19017
+
19018
+ res.json({
19019
+ success: true,
19020
+ storeCart: {
19021
+ storeId: storeId,
19022
+ storeName: storeCart.storeName,
19023
+ items: storeCart.items,
19024
+ subtotal: storeCart.subtotal,
19025
+ itemCount: storeCart.itemCount
19026
+ }
19027
+ });
19028
+ } catch (error) {
19029
+ res.status(500).json({ error: 'Failed to fetch store cart' });
19030
+ }
19031
+ });
19032
+
19033
+ // ============================================
19034
+ // 6. DELETE /api/cart/clear-all - تفريغ كل السلة
19035
+ // ============================================
19036
+ app.delete('/api/cart/clear-all', authenticateToken, async (req, res) => {
19037
+ try {
19038
+ await Cart.findOneAndDelete({ userId: req.user.userId });
19039
+
19040
+ res.json({
19041
+ success: true,
19042
+ message: 'Cart cleared successfully'
19043
+ });
19044
+
19045
+ } catch (error) {
19046
+ console.error('Error clearing cart:', error);
19047
+ res.status(500).json({ error: 'Failed to clear cart' });
19048
+ }
19049
+ });
19050
+
19051
+ // ============================================
19052
+ // 7. GET /api/cart/summary - ملخص سريع للسلة
19053
+ // ============================================
19054
+ app.get('/api/cart/summary', authenticateToken, async (req, res) => {
19055
+ try {
19056
+ const cart = await Cart.findOne({ userId: req.user.userId });
19057
+
19058
+ if (!cart) {
19059
+ return res.json({
19060
+ success: true,
19061
+ summary: {
19062
+ totalItems: 0,
19063
+ totalStores: 0,
19064
+ stores: []
19065
+ }
19066
+ });
19067
+ }
19068
+
19069
+ const storesSummary = [];
19070
+ for (let [storeId, storeData] of cart.stores) {
19071
+ storesSummary.push({
19072
+ storeId: storeId,
19073
+ storeName: storeData.storeName,
19074
+ itemCount: storeData.itemCount,
19075
+ subtotal: storeData.subtotal
19076
+ });
19077
+ }
19078
+
19079
+ res.json({
19080
+ success: true,
19081
+ summary: {
19082
+ totalItems: cart.totalItems,
19083
+ totalStores: cart.totalStores,
19084
+ stores: storesSummary
19085
+ }
19086
+ });
19087
+
19088
  } catch (error) {
19089
+ console.error('Error fetching cart summary:', error);
19090
+ res.status(500).json({ error: 'Failed to fetch cart summary' });
19091
  }
19092
  });
19093