90 lines
8.6 KiB
JavaScript
90 lines
8.6 KiB
JavaScript
require('reflect-metadata');
|
|
const fs = require('node:fs');
|
|
const { randomBytes } = require('node:crypto');
|
|
const env = require('dotenv').parse(fs.readFileSync('.env'));
|
|
const { cardPng } = require('./seed-demo');
|
|
const base = 'https://oudelaa-api1-web-35ee485c.hosted.cumin.dev/api/v1';
|
|
const privateFile = '.demo-api-private.json';
|
|
const stateFile = 'deliverables/demo-api-progress.json';
|
|
fs.mkdirSync('deliverables', { recursive: true });
|
|
const secret = fs.existsSync(privateFile) ? JSON.parse(fs.readFileSync(privateFile)) : { password: randomBytes(24).toString('base64url') };
|
|
if (!fs.existsSync(privateFile)) fs.writeFileSync(privateFile, JSON.stringify(secret), { flag: 'wx' });
|
|
const state = fs.existsSync(stateFile) ? JSON.parse(fs.readFileSync(stateFile)) : { base, done: {}, pending: null };
|
|
if (state.base !== base) throw new Error('Target mismatch');
|
|
const save = () => fs.writeFileSync(stateFile, JSON.stringify(state, null, 2));
|
|
const id = (x) => x?._id || x?.id;
|
|
const tokens = [];
|
|
async function api(route, method = 'GET', body, token) {
|
|
const form = body instanceof FormData;
|
|
const r = await fetch(base + route, { method, redirect: 'error', signal: AbortSignal.timeout(40000),
|
|
headers: { ...(token ? { Authorization: `Bearer ${token}` } : {}), ...(!form && body ? { 'Content-Type': 'application/json' } : {}) },
|
|
body: body ? form ? body : JSON.stringify(body) : undefined });
|
|
const raw = await r.text(); let data; try { data = JSON.parse(raw); } catch {}
|
|
if (!r.ok) { const e = new Error(`HTTP ${r.status} ${method} ${route}`); e.status = r.status; e.detail = typeof data?.message === 'string' ? data.message : Array.isArray(data?.message) ? data.message.join('; ') : ''; throw e; }
|
|
return data?.meta && data?.data ? data.data : data;
|
|
}
|
|
function multipart(fields, fileField, i = 0) {
|
|
const f = new FormData(); for (const [k,v] of Object.entries(fields)) f.append(k, Array.isArray(v) ? JSON.stringify(v) : String(v));
|
|
if (fileField) f.append(fileField, new Blob([cardPng(i)], { type: 'image/png' }), `demo-${i}.png`);
|
|
return f;
|
|
}
|
|
async function once(key, action) {
|
|
if (state.done[key]) return state.done[key];
|
|
if (state.pending) throw new Error('Ambiguous previous write; reconcile progress before retry');
|
|
state.pending = key; save();
|
|
try { const result = await action(); state.done[key] = result || { ok: true }; state.pending = null; save(); console.log('Created ' + key); return result; }
|
|
catch(e) { if (e.status && e.status < 500) { state.pending = null; save(); } throw e; }
|
|
}
|
|
(async () => {
|
|
const admin = await api('/auth/superadmin/login', 'POST', { email: env.SUPERADMIN_EMAIL, password: env.SUPERADMIN_PASSWORD });
|
|
tokens.push({ ...admin, superadmin: true }); const root = admin.accessToken;
|
|
if(state.pending?.startsWith('user-')) {
|
|
const i=Number(state.pending.slice(5));
|
|
const found=await api(`/users/admin?q=oud_api_demo_${i+1}&limit=100`,'GET',undefined,root);
|
|
const matches=(found.items||[]).filter(u=>u.username===`oud_api_demo_${i+1}` && u.email===`oudelaa-api-demo-${i+1}@example.invalid`);
|
|
if(matches.length>1) throw new Error('Ambiguous duplicate account');
|
|
if(matches.length===1) state.done[state.pending]=matches[0];
|
|
state.pending=null;save();
|
|
}
|
|
const names = ['متجر أوتار','بيت المقام','ركن الإيقاع','استوديو النغم','سارة النجار','عمر العلي','ليان حسن','رامي يوسف','نور خالد','زيد سالم','مريم أحمد','آدم كريم'];
|
|
const users = [];
|
|
for (let i=0;i<12;i++) {
|
|
const email = `oudelaa-api-demo-${i+1}@example.invalid`;
|
|
const u = await once(`user-${i}`, () => api('/users/admin/create-admin','POST',{name:names[i]+' — تجريبي',username:`oud_api_demo_${i+1}`,email,password:secret.password,confirmPassword:secret.password},root));
|
|
if(i>=4) await once(`role-${i}`,()=>api(`/users/admin/${id(u)}/role`,'PATCH',{role:'user'},root));
|
|
await once(`profile-${i}`,()=>api(`/users/admin/${id(u)}`,'PATCH',{bio:'حساب تجريبي لاختبار أودلا، ليست جهة حقيقية.',location:'الرياض',musicGenres:['Tarab','Pop'],favoriteInstruments:['Oud'],musicRoles:['instrumentalist']},root));
|
|
const login = await api('/auth/login','POST',{email,password:secret.password}); tokens.push(login); users.push({id:id(u),token:login.accessToken});
|
|
}
|
|
for(let i=0;i<4;i++) {
|
|
await once(`shop-${i}`,()=>api(`/marketplace/superadmin/admins/${users[i].id}/shop-profile`,'PATCH',multipart({shopName:names[i]+' — تجريبي',shopDescription:'متجر تجريبي، لا بيع أو توصيل فعلي.',shopLocation:'الرياض',shopPhone:'0000000000',shopDeliveryAvailable:false,shopReturnPolicy:'منتجات اختبار فقط'},'shopImageFiles',i),root));
|
|
await once(`repair-${i}`,()=>api(`/marketplace/superadmin/admins/${users[i].id}/repair-shops`,'POST',multipart({name:`ورشة تجريبية ${i+1}`,description:'ورشة اختبار لا تقدم خدمة فعلية.',location:'الرياض',services:['ضبط الأوتار','الصيانة'],isActive:true},'imageFiles',i),root));
|
|
}
|
|
const titles=['عود شرقي','غيتار كلاسيكي','كمان','بيانو رقمي','طبلة','ناي','حقيبة آلة','أوتار عود','ميكروفون','دفتر نوتات'];
|
|
for(let i=0;i<40;i++) await once(`product-${i}`,()=>api(`/marketplace/superadmin/admins/${users[i%4].id}/listings`,'POST',multipart({title:`${titles[i%10]} ${i+1} — تجريبي`,description:'منتج اختبار فقط، غير معروض للبيع الحقيقي.',price:100+i*25,quantity:20,currency:'SAR',condition:i%2?'used':'new',listingCategory:i%10<6?'musical_instrument':i%10<8?'accessory':i%10===8?'audio_gear':'sheet_music',instrumentType:titles[i%10],isActive:true},'imageFiles',i%8),root));
|
|
for(let i=0;i<24;i++) await once(`post-${i}`,()=>api('/posts','POST',multipart({content:`منشور تجريبي ${i+1}: نتدرب على الموسيقى والمقامات #تجريبي`},i%2?'imageFiles':null,i%8),users[i%12].token));
|
|
for(let i=0;i<12;i++) {
|
|
const t=users[(i+1)%12].token, p=id(state.done[`post-${i}`]);
|
|
await once(`like-${i}`,()=>api('/likes','POST',{targetType:'post',targetId:p},t));
|
|
await once(`comment-${i}`,()=>api('/comments','POST',{postId:p,content:'تعليق تجريبي: عزف جميل!'},t));
|
|
await once(`save-${i}`,()=>api('/saves','POST',{postId:p},t));
|
|
await once(`follow-${i}`,()=>api(`/users/${users[i].id}/follow`,'POST',undefined,t));
|
|
}
|
|
for(let i=0;i<8;i++) {
|
|
const t=users[i+4].token;
|
|
await once(`draft-${i}`,()=>api('/posts/drafts','POST',multipart({content:`مسودة تجريبية ${i+1}`,type:'text',isDraft:true}),t));
|
|
await once(`report-${i}`,()=>api('/reports','POST',{targetType:'post',targetId:id(state.done[`post-${i}`]),reason:'other',details:'بلاغ تجريبي على محتوى تجريبي فقط.'},t));
|
|
}
|
|
for(let i=0;i<3;i++) {
|
|
const a=users[i+4],b=users[i+7];
|
|
const c=await once(`chat-${i}`,()=>api('/chat/conversations','POST',{participantIds:[b.id]},a.token));
|
|
for(let j=0;j<3;j++) await once(`message-${i}-${j}`,()=>api('/chat/messages','POST',{conversationId:id(c),content:`رسالة تجريبية ${j+1} للتدريب الموسيقي.`},j%2?b.token:a.token));
|
|
await once(`support-${i}`,()=>api('/support/tickets','POST',{subject:`تذكرة اختبار ${i+1}`,message:'طلب دعم تجريبي فقط.',category:'technical'},a.token));
|
|
await once(`case-${i}`,()=>api('/superadmin/cases','POST',{title:`حالة مراجعة تجريبية ${i+1}`,caseType:'report_review',resourceType:'report',resourceId:id(state.done[`report-${i}`]),description:'اختبار لوحة الإدارة',status:['open','in_review','resolved'][i]},root));
|
|
await once(`collaboration-${i}`,()=>api(`/posts/${id(state.done[`post-${i+7}`])}/collaboration-requests`,'POST',multipart({targetUserId:b.id,collaborationType:'duet',message:'طلب تعاون تجريبي.'}),a.token));
|
|
}
|
|
for(let i=0;i<6;i++) await once(`order-${i}`,()=>api('/orders','POST',{listingId:id(state.done[`product-${i}`]),quantity:1,customerName:'عميل تجريبي',customerPhone:'0000000000',note:'طلب اختبار فقط؛ لا شحن ولا تحصيل.'},users[i+4].token));
|
|
const home=await api('/marketplace/home'); console.log(JSON.stringify({completed:true,summary:home.summary,operations:Object.keys(state.done).length}));
|
|
})().catch(e=>{console.error(JSON.stringify({error:e.message,detail:e.detail||undefined,pending:state.pending}));process.exitCode=1;}).finally(async()=>{
|
|
for(const t of tokens) { try { await api(t.superadmin?'/auth/superadmin/logout':'/auth/logout','POST',{refreshToken:t.refreshToken},t.accessToken); }catch{} }
|
|
});
|