194 lines
16 KiB
JavaScript
194 lines
16 KiB
JavaScript
// Run with node -r ts-node/register scripts/seed-demo.js
|
|
// No application bootstrap: never dispatch email, payment, push or socket events.
|
|
require('reflect-metadata');
|
|
const mongoose = require('mongoose');
|
|
const bcrypt = require('bcrypt');
|
|
const { createHash, randomBytes } = require('node:crypto');
|
|
const fs = require('node:fs');
|
|
const path = require('node:path');
|
|
const { deflateSync } = require('node:zlib');
|
|
const seed = 'oudelaa-demo-v1';
|
|
const id = (kind, index) => new mongoose.Types.ObjectId(createHash('sha256').update(`${seed}:${kind}:${index}`).digest('hex').slice(0, 24));
|
|
const schemas = {
|
|
User: ['users/user', 'User'], Instrument: ['marketplace/instrument', 'Instrument'], RepairShop: ['marketplace/repair-shop', 'RepairShop'],
|
|
Post: ['posts/post', 'Post'], Comment: ['comments/comment', 'Comment'], Like: ['likes/like', 'Like'], Save: ['saves/save', 'Save'],
|
|
Follow: ['follows/follow', 'Follow'], Conversation: ['chat/conversation', 'Conversation'], Message: ['chat/message', 'Message'],
|
|
Notification: ['notifications/notification', 'Notification'], Order: ['orders/order', 'Order'], CartItem: ['orders/cart', 'CartItem'],
|
|
SupportTicket: ['support/support-ticket', 'SupportTicket'], SupportTicketMessage: ['support/support-ticket-message', 'SupportTicketMessage'],
|
|
CollaborationRequest: ['collaboration-requests/collaboration-request', 'CollaborationRequest'],
|
|
Report: ['reports/report', 'Report'], SuperAdminCase: ['superadmin/superadmin-case', 'SuperAdminCase'],
|
|
FollowRequest: ['follows/follow-request', 'FollowRequest'],
|
|
};
|
|
function modelsFor(connection) {
|
|
const models = Object.fromEntries(Object.entries(schemas).map(([name, [file, exported]]) => {
|
|
const [module, filename] = file.split('/');
|
|
const schema = require(`../src/modules/${module}/schemas/${filename}.schema.ts`)[`${exported}Schema`].clone();
|
|
schema.add({ demoSeed: { type: String, select: false } });
|
|
return [name, connection.model(name, schema)];
|
|
}));
|
|
models.PostDraft = connection.model('PostDraft', new mongoose.Schema({
|
|
authorId: { type: mongoose.Schema.Types.ObjectId, required: true },
|
|
content: String, type: { type: String, enum: ['text'] },
|
|
isDraft: { type: Boolean, enum: [true], required: true },
|
|
status: { type: String, enum: ['draft'], required: true },
|
|
demoSeed: String, createdAt: Date, updatedAt: Date,
|
|
}, { collection: 'postdrafts', versionKey: false }));
|
|
return models;
|
|
}
|
|
const image = (index) => `/uploads/${seed}/card-${index % 8}.png`;
|
|
function buildDataset(passwordHash) {
|
|
const rows = Object.fromEntries([...Object.keys(schemas), 'PostDraft'].map((name) => [name, []]));
|
|
const now = new Date();
|
|
const add = (kind, index, data) => {
|
|
const doc = { _id: id(kind, index), ...data, demoSeed: seed, createdAt: new Date(now.getTime() - (250 - index) * 3600000), updatedAt: now };
|
|
rows[kind].push(doc); return doc;
|
|
};
|
|
const cities = ['الرياض', 'جدة', 'الدمام', 'الخبر'];
|
|
const names = ['متجر أوتار', 'بيت المقام', 'ركن الإيقاع', 'استوديو النغم', 'سارة النجار', 'عمر العلي', 'ليان حسن', 'رامي يوسف', 'نور خالد', 'زيد سالم', 'مريم أحمد', 'آدم كريم'];
|
|
for (let i = 0; i < 12; i++) add('User', i, {
|
|
name: `${names[i]} — تجريبي`, username: `oud_demo_${i + 1}`, email: `oudelaa-demo-${i + 1}@example.invalid`, password: passwordHash,
|
|
role: i < 4 ? 'admin' : 'user', isEmailVerified: true, avatar: image(i), coverImage: image(i + 1), location: cities[i % 4],
|
|
bio: 'حساب وبيانات تجريبية لاختبار واجهات أودلا. ليست جهة حقيقية.', musicRoles: ['instrumentalist'],
|
|
musicGenres: ['طرب', 'موسيقى عربية'], favoriteInstruments: ['عود', 'بيانو'], favoriteMaqamat: ['بيات', 'راست'],
|
|
postsCount: 2, followersCount: 1, followingCount: 1,
|
|
...(i < 4 ? { shopName: `${names[i]} — تجريبي`, shopDescription: 'متجر موسيقي تجريبي. المنتجات والأسعار للعرض والاختبار فقط.',
|
|
shopLocation: cities[i], shopLatitude: 24.7136 + i * 0.01, shopLongitude: 46.6753 + i * 0.01,
|
|
shopImageUrls: [image(i)], shopLogoUrl: image(i), shopCoverUrl: image(i + 1), shopDeliveryAvailable: true, shopDeliveryFee: 25,
|
|
shopTrialPolicy: 'سياسة تجريبية: تجربة الآلة قبل الاستلام.', shopReturnPolicy: 'بيانات اختبار فقط؛ لا يوجد بيع فعلي.' } : {}),
|
|
});
|
|
const products = [
|
|
['عود شرقي', 'oud', 'musical_instrument', 1250], ['غيتار كلاسيكي', 'guitar', 'musical_instrument', 650],
|
|
['كمان للمبتدئين', 'violin', 'musical_instrument', 480], ['بيانو رقمي', 'piano', 'musical_instrument', 3200],
|
|
['طبلة شرقية', 'percussion', 'musical_instrument', 220], ['ناي خشبي', 'ney', 'musical_instrument', 175],
|
|
['حقيبة آلة موسيقية', 'case', 'accessory', 95], ['أوتار عود', 'strings', 'accessory', 65],
|
|
['ميكروفون استوديو', 'microphone', 'audio_gear', 450], ['دفتر نوتات', 'sheet_music', 'sheet_music', 45],
|
|
];
|
|
for (let i = 0; i < 40; i++) {
|
|
const [title, instrumentType, listingCategory, price] = products[i % 10];
|
|
add('Instrument', i, { ownerAdminId: id('User', i % 4), title: `${title} ${Math.floor(i / 10) + 1} — تجريبي`,
|
|
description: 'منتج تجريبي لاختبار العرض والفلترة والسلة. غير معروض للبيع الحقيقي.', price: price + Math.floor(i / 10) * 20,
|
|
quantity: i % 13 === 0 ? 0 : 5 + i, currency: 'SAR', condition: ['new', 'like_new', 'used', 'refurbished'][i % 4],
|
|
listingCategory, instrumentType, imageUrls: [image(i), image(i + 1)], isActive: true });
|
|
}
|
|
for (let i = 0; i < 4; i++) add('RepairShop', i, { ownerAdminId: id('User', i), name: `ورشة النغم ${i + 1} — تجريبي`,
|
|
description: 'ورشة صيانة تجريبية، لا تقدم خدمات فعلية.', services: ['ضبط الأوتار', 'صيانة الآلات', 'تبديل القطع'],
|
|
location: cities[i % 4], latitude: 24.7136 + i * 0.01, longitude: 46.6753 + i * 0.01, imageUrls: [image(i)] });
|
|
for (let i = 0; i < 24; i++) {
|
|
add('Post', i, { authorId: id('User', i % 12), content: `منشور تجريبي ${i + 1}: شاركونا مقاماتكم وآلاتكم المفضلة #موسيقى #تجريبي`,
|
|
postType: i % 2 ? 'image' : 'text', imageUrls: i % 2 ? [image(i)] : [], hashtags: ['موسيقى', 'تجريبي'],
|
|
likesCount: 1, commentsCount: 1, savesCount: i < 12 ? 1 : 0, location: cities[i % 4] });
|
|
add('Comment', i, { postId: id('Post', i), authorId: id('User', (i + 1) % 12), content: 'تعليق تجريبي: عزف جميل، بانتظار المزيد!' });
|
|
add('Like', i, { userId: id('User', (i + 2) % 12), targetId: id('Post', i), targetType: 'post' });
|
|
}
|
|
for (let i = 0; i < 12; i++) {
|
|
add('Save', i, { userId: id('User', i), postId: id('Post', i) });
|
|
add('Follow', i, { followerId: id('User', i), followingId: id('User', (i + 1) % 12) });
|
|
add('Notification', i, { recipientId: id('User', i), actorId: id('User', (i + 2) % 12), type: 'like', referenceId: id('Post', i),
|
|
title: 'إعجاب تجريبي', previewText: 'تفاعل أحد المستخدمين التجريبيين مع منشورك', resourceType: 'post', deepLink: `/posts/${id('Post', i)}` });
|
|
}
|
|
for (let i = 0; i < 3; i++) {
|
|
const a = id('User', i + 4), b = id('User', i + 7);
|
|
add('Conversation', i, { participantIds: [a, b], createdBy: a, lastMessageId: id('Message', i * 3 + 2),
|
|
lastMessageText: 'إلى اللقاء في التدريب التجريبي!', lastMessageAt: now, unreadCountByUser: { [String(a)]: 1, [String(b)]: 0 } });
|
|
for (let j = 0; j < 3; j++) add('Message', i * 3 + j, { conversationId: id('Conversation', i), senderId: j % 2 ? a : b,
|
|
content: ['مرحبًا، هذه محادثة تجريبية.', 'هل نجرب مقام البيات؟', 'إلى اللقاء في التدريب التجريبي!'][j], seenBy: [j % 2 ? a : b] });
|
|
add('SupportTicket', i, { userId: a, subject: `تذكرة اختبار ${i + 1}`, category: 'technical', status: ['open', 'in_progress', 'resolved'][i] });
|
|
add('SupportTicketMessage', i, { ticketId: id('SupportTicket', i), senderId: a, senderRole: 'user', message: 'رسالة تجريبية لاختبار واجهة الدعم.' });
|
|
add('CollaborationRequest', i, { requesterId: a, targetUserId: b, postId: id('Post', i), collaborationType: 'duet',
|
|
status: ['pending', 'approved', 'rejected'][i], message: 'دعوة تجريبية لعزف مشترك.' });
|
|
}
|
|
for (let i = 0; i < 6; i++) {
|
|
const product = rows.Instrument[i + 1];
|
|
const status = ['pending', 'confirmed', 'processing', 'ready', 'completed', 'cancelled'][i];
|
|
add('Order', i, { orderNumber: `DEMO-V1-${String(i + 1).padStart(4, '0')}`, buyerId: id('User', i + 4), sellerAdminId: product.ownerAdminId,
|
|
listingId: product._id, itemTitle: product.title, itemType: product.instrumentType, itemImageUrl: product.imageUrls[0], quantity: 1,
|
|
unitPrice: product.price, total: product.price, subtotal: product.price, customerName: `${names[i + 4]} — تجريبي`, customerPhone: '0000000000',
|
|
city: cities[i % 4], note: 'طلب تجريبي، لا شحن أو تحصيل فعلي.', status, statusHistory: [{ status, at: now, note: 'Demo fixture' }],
|
|
items: [{ listingId: product._id, title: product.title, quantity: 1, unitPrice: product.price, total: product.price, imageUrl: product.imageUrls[0] }] });
|
|
}
|
|
for (let i = 0; i < 4; i++) add('CartItem', i, { buyerId: id('User', i + 4), listingId: id('Instrument', i + 1), quantity: 1 });
|
|
for (let i = 0; i < 8; i++) {
|
|
add('PostDraft', i, { authorId: id('User', i + 4), content: `مسودة تجريبية خاصة ${i + 1}`, type: 'text', isDraft: true, status: 'draft' });
|
|
const status = ['open', 'in_review', 'resolved', 'rejected'][i % 4];
|
|
add('Report', i, { reporterId: id('User', i + 4), targetType: 'post', targetId: id('Post', i), reason: 'other',
|
|
details: 'بلاغ تجريبي على منشور تجريبي لاختبار لوحة الإدارة.', status,
|
|
...(status === 'resolved' || status === 'rejected' ? { resolutionNote: 'نتيجة تجريبية فقط', resolvedBy: 'demo-seed', resolvedAt: now } : {}) });
|
|
}
|
|
for (let i = 0; i < 3; i++) {
|
|
add('SuperAdminCase', i, { title: `حالة مراجعة تجريبية ${i + 1}`, description: 'بيانات اختبار فقط',
|
|
caseType: 'report_review', resourceType: 'report', resourceId: String(id('Report', i)),
|
|
status: ['open', 'in_review', 'resolved'][i], priority: ['low', 'normal', 'high'][i],
|
|
createdBy: 'demo-seed', tags: ['demo'], resolution: i === 2 ? 'أغلقت للتجربة' : '' });
|
|
add('FollowRequest', i, { requesterId: id('User', i + 4), targetUserId: id('User', i + 8), status: 'pending' });
|
|
}
|
|
return rows;
|
|
}
|
|
|
|
// Small locally generated PNG illustrations, no external image dependencies.
|
|
function cardPng(index) {
|
|
const width = 400, height = 300;
|
|
const pixels = Buffer.alloc((width * 3 + 1) * height);
|
|
for (let y = 0; y < height; y++) for (let x = 0; x < width; x++) {
|
|
const at = y * (width * 3 + 1) + 1 + x * 3;
|
|
const body = ((x - 200) / 62) ** 2 + ((y - 195) / 70) ** 2 < 1;
|
|
const neck = x >= 193 && x <= 207 && y > 25 && y < 170;
|
|
const hole = (x - 200) ** 2 + (y - 175) ** 2 < 17 ** 2;
|
|
const color = hole ? [38, 31, 25] : body || neck ? [150 + index * 8, 95, 48] : [235 - index * 4, 239 - index * 2, 245];
|
|
color.forEach((v, c) => { pixels[at + c] = v; });
|
|
}
|
|
const crc = (buffer) => { let n = 0xffffffff; for (const byte of buffer) { n ^= byte; for (let bit = 0; bit < 8; bit++) n = (n >>> 1) ^ ((n & 1) ? 0xedb88320 : 0); } return (n ^ 0xffffffff) >>> 0; };
|
|
const chunk = (type, data) => { const label = Buffer.from(type), size = Buffer.alloc(4), checksum = Buffer.alloc(4); size.writeUInt32BE(data.length); checksum.writeUInt32BE(crc(Buffer.concat([label, data]))); return Buffer.concat([size, label, data, checksum]); };
|
|
const header = Buffer.alloc(13); header.writeUInt32BE(width); header.writeUInt32BE(height, 4); header[8] = 8; header[9] = 2;
|
|
return Buffer.concat([Buffer.from([137,80,78,71,13,10,26,10]), chunk('IHDR', header), chunk('IDAT', deflateSync(pixels)), chunk('IEND', Buffer.alloc(0))]);
|
|
}
|
|
|
|
async function main() {
|
|
const apply = process.argv.includes('--apply');
|
|
const password = process.env.DEMO_PASSWORD;
|
|
if (apply && (!password || password.length < 20)) throw new Error('Set DEMO_PASSWORD (20+ characters) privately before applying.');
|
|
const rows = buildDataset(await bcrypt.hash(password || randomBytes(32).toString('hex'), 12));
|
|
const connection = mongoose.createConnection();
|
|
const models = modelsFor(connection);
|
|
// Cast and validate every document using the real application schemas before connecting.
|
|
const prepared = {};
|
|
for (const [name, docs] of Object.entries(rows)) {
|
|
prepared[name] = [];
|
|
for (const data of docs) { const doc = new models[name](data); await doc.validate(); prepared[name].push(doc.toObject({ transform: false })); }
|
|
}
|
|
const counts = Object.fromEntries(Object.entries(rows).map(([name, docs]) => [name, docs.length]));
|
|
console.log(JSON.stringify({ seed, mode: apply ? 'apply' : 'dry-run', counts, total: Object.values(counts).reduce((a,b) => a+b,0) }, null, 2));
|
|
if (!apply) { await connection.close(); return; }
|
|
const uri = process.env.DEMO_MONGODB_URI;
|
|
const expected = process.argv.find((arg) => arg.startsWith('--expected-db='))?.slice('--expected-db='.length);
|
|
if (!uri || !expected) throw new Error('Explicit DEMO_MONGODB_URI and --expected-db=<database> are required. MONGODB_URI/.env are never loaded implicitly.');
|
|
try {
|
|
await connection.openUri(uri, { autoIndex: false, serverSelectionTimeoutMS: 10000 });
|
|
if (connection.name !== expected) throw new Error('Database name differs from --expected-db; no data inserted.');
|
|
// Precreate only fixture collections so transactions work on fresh replica sets too.
|
|
for (const model of Object.values(models)) await model.createCollection();
|
|
const session = await connection.startSession();
|
|
let inserted = 0;
|
|
try {
|
|
await session.withTransaction(async () => {
|
|
inserted = 0;
|
|
for (const [name, docs] of Object.entries(prepared)) {
|
|
for (const doc of docs) {
|
|
const existing = await models[name].collection.findOne({ _id: doc._id }, { session, projection: { demoSeed: 1 } });
|
|
if (existing && existing.demoSeed !== seed) throw new Error(`ID collision in ${name}; transaction aborted.`);
|
|
}
|
|
const result = await models[name].collection.bulkWrite(docs.map((doc) => ({ updateOne: {
|
|
filter: { _id: doc._id, demoSeed: seed }, update: { $setOnInsert: doc }, upsert: true,
|
|
} })), { session, ordered: true });
|
|
inserted += result.upsertedCount;
|
|
}
|
|
});
|
|
} finally { await session.endSession(); }
|
|
const assetDir = path.resolve(__dirname, '..', 'uploads', seed); fs.mkdirSync(assetDir, { recursive: true });
|
|
for (let i = 0; i < 8; i++) fs.writeFileSync(path.join(assetDir, `card-${i}.png`), cardPng(i));
|
|
console.log(JSON.stringify({ database: connection.name, inserted, existingUntouched: Object.values(counts).reduce((a,b)=>a+b,0) - inserted,
|
|
assets: `uploads/${seed}`, accounts: rows.User.map(({ email, role }) => ({ email, role })) }, null, 2));
|
|
} finally { await connection.close(); }
|
|
}
|
|
if (require.main === module) main().catch(() => { console.error('Demo seed failed. Check database name, replica-set access, unique account conflicts and schema validation. No credentials are logged.'); process.exitCode = 1; });
|
|
module.exports = { buildDataset, modelsFor, cardPng, id, seed };
|