843 lines
30 KiB
TypeScript
843 lines
30 KiB
TypeScript
import { INestApplication, ValidationPipe } from '@nestjs/common';
|
||
import { ConfigService } from '@nestjs/config';
|
||
import { JwtService } from '@nestjs/jwt';
|
||
import { getConnectionToken } from '@nestjs/mongoose';
|
||
import { Test } from '@nestjs/testing';
|
||
import { mkdtemp, writeFile } from 'node:fs/promises';
|
||
import { tmpdir } from 'node:os';
|
||
import { join } from 'node:path';
|
||
import { Connection, Types } from 'mongoose';
|
||
import * as request from 'supertest';
|
||
import type { Response } from 'supertest';
|
||
import { SUPERADMIN_PERMISSIONS } from '../src/modules/superadmin/superadmin-permissions';
|
||
import {
|
||
MusicCommerceStore,
|
||
musicIndexes,
|
||
} from '../src/modules/music-commerce/music-commerce.store';
|
||
|
||
const integration = process.env.E2E_MONGODB_URI ? describe : describe.skip;
|
||
|
||
integration('Music World HTTP contracts and concurrency', () => {
|
||
jest.setTimeout(120_000);
|
||
let app: INestApplication;
|
||
let database: Connection;
|
||
let store: MusicCommerceStore;
|
||
let admin: string;
|
||
let student: string;
|
||
let secondStudent: string;
|
||
const studentId = new Types.ObjectId();
|
||
const secondStudentId = new Types.ObjectId();
|
||
const examples: {
|
||
name: string;
|
||
method: string;
|
||
path: string;
|
||
request?: Record<string, unknown>;
|
||
status: number;
|
||
response: unknown;
|
||
}[] = [];
|
||
const iso = (hours: number) => new Date(Date.now() + hours * 3600000).toISOString();
|
||
const schedule = () => ({ startsAt: iso(96), endsAt: iso(100), timeZone: 'Asia/Riyadh' });
|
||
const sale = () => ({ salesStartAt: iso(-5), salesEndAt: iso(90) });
|
||
const server = () => request(app.getHttpServer());
|
||
const call = (
|
||
method: 'get' | 'post' | 'put' | 'delete' | 'patch',
|
||
path: string,
|
||
token = student,
|
||
) =>
|
||
server()
|
||
[method]('/api/v1' + path)
|
||
.set('Authorization', 'Bearer ' + token);
|
||
const adminCall = (method: 'post' | 'patch' | 'get', path: string) =>
|
||
call(method, '/superadmin/music-world' + path, admin);
|
||
const save = (
|
||
name: string,
|
||
method: string,
|
||
path: string,
|
||
result: Response,
|
||
body?: Record<string, unknown>,
|
||
) => {
|
||
if (!examples.some((entry) => entry.name === name)) {
|
||
examples.push({
|
||
name,
|
||
method,
|
||
path,
|
||
request: body,
|
||
status: result.status,
|
||
response: result.body,
|
||
});
|
||
}
|
||
return result.body;
|
||
};
|
||
|
||
beforeAll(async () => {
|
||
const uri = new URL(process.env.E2E_MONGODB_URI!);
|
||
uri.pathname = '/music_world_e2e_' + new Types.ObjectId().toHexString();
|
||
const localMediaDir = await mkdtemp(join(tmpdir(), 'oudelaa-lessons-e2e-'));
|
||
await writeFile(join(localMediaDir, 'oud.mp4'), Buffer.alloc(256, 7));
|
||
Object.assign(process.env, {
|
||
MONGODB_URI: uri.toString(),
|
||
SEARCH_ENGINE: 'regex',
|
||
MUSIC_WORLD_SANDBOX_PAYMENTS: 'true',
|
||
MUSIC_WORLD_EXPIRY_WORKER: 'false',
|
||
MUSIC_WORLD_PRIVATE_MEDIA_DIR: localMediaDir,
|
||
MUSIC_WORLD_DISCOVERY_TYPES:
|
||
'users,talents,posts,hashtags,events,products,instruments,shops,repair_shops,institutes,instructors,courses,lessons,opportunities',
|
||
MUSIC_WORLD_DISCOVERY_MIN_VERSIONS: 'courses:1.2.0',
|
||
});
|
||
const { AppModule } = await import('../src/app.module');
|
||
const module = await Test.createTestingModule({ imports: [AppModule] }).compile();
|
||
app = module.createNestApplication();
|
||
app.setGlobalPrefix('api/v1');
|
||
app.useGlobalPipes(
|
||
new ValidationPipe({
|
||
whitelist: true,
|
||
forbidNonWhitelisted: true,
|
||
transform: true,
|
||
transformOptions: { enableImplicitConversion: true },
|
||
}),
|
||
);
|
||
await app.listen(0, '127.0.0.1');
|
||
database = app.get(getConnectionToken());
|
||
store = app.get(MusicCommerceStore);
|
||
for (const [collection, indexes] of Object.entries(musicIndexes)) {
|
||
await database.collection(collection).createIndexes(indexes);
|
||
}
|
||
await database.collection('users').insertMany([
|
||
{
|
||
_id: studentId,
|
||
name: 'Oud Learner',
|
||
username: 'oud_learner',
|
||
email: 'oud_learner@example.invalid',
|
||
role: 'user',
|
||
isDisabled: false,
|
||
isPrivate: false,
|
||
musicRoles: ['composer'],
|
||
followersCount: 2,
|
||
},
|
||
{
|
||
_id: secondStudentId,
|
||
name: 'Oud Partner',
|
||
username: 'oud_partner',
|
||
email: 'oud_partner@example.invalid',
|
||
role: 'user',
|
||
isDisabled: false,
|
||
isPrivate: false,
|
||
musicRoles: ['composer'],
|
||
followersCount: 3,
|
||
},
|
||
]);
|
||
const jwt = new JwtService();
|
||
const token = (sub: Types.ObjectId) =>
|
||
jwt.sign(
|
||
{ sub: String(sub), tokenType: 'access' },
|
||
{ secret: process.env.JWT_ACCESS_SECRET, expiresIn: 1200 },
|
||
);
|
||
student = token(studentId);
|
||
secondStudent = token(secondStudentId);
|
||
admin = jwt.sign(
|
||
{
|
||
sub: 'test-admin',
|
||
tokenType: 'superadmin_access',
|
||
permissions: [SUPERADMIN_PERMISSIONS.MUSIC_WORLD_MANAGE],
|
||
},
|
||
{ secret: process.env.SUPERADMIN_ACCESS_SECRET, expiresIn: 1200 },
|
||
);
|
||
});
|
||
|
||
afterAll(async () => {
|
||
if (app) await app.close();
|
||
if (process.env.MUSIC_WORLD_CAPTURE_EXAMPLES === '1' && examples.length) {
|
||
await writeFile(
|
||
'postman/music-world-response-examples.json',
|
||
JSON.stringify(
|
||
{
|
||
source:
|
||
'Captured through the HTTP API using synthetic users and catalog records on an isolated MongoDB replica set. Playback link signature redacted.',
|
||
examples,
|
||
},
|
||
null,
|
||
2,
|
||
) + '\n',
|
||
);
|
||
}
|
||
});
|
||
|
||
const eventPayload = (priceMinor = 900, capacity = 1) => ({
|
||
title: 'حفل عود Oud Concert',
|
||
description: 'Test catalog',
|
||
category: 'Tarab',
|
||
venueName: 'Test Hall',
|
||
place: { location: 'Riyadh', latitude: 24.71, longitude: 46.67 },
|
||
...schedule(),
|
||
currency: 'SAR',
|
||
imageUrls: ['/uploads/music-event.jpg'],
|
||
videoUrls: [],
|
||
participants: [{ name: 'Oud Quartet' }],
|
||
organizers: [{ name: 'Music World' }],
|
||
ticketCategories: [
|
||
{
|
||
name: 'Standard',
|
||
benefits: ['General admission'],
|
||
priceMinor,
|
||
capacity,
|
||
maxPerBooking: 1,
|
||
...sale(),
|
||
},
|
||
],
|
||
});
|
||
|
||
it('validates, lists, filters and saves events with a measured distance', async () => {
|
||
await server().get('/api/v1/events').expect(401);
|
||
await call('post', '/superadmin/music-world/events').send(eventPayload()).expect(401);
|
||
await adminCall('post', '/events')
|
||
.send({ ...eventPayload(), timeZone: 'Invalid/Zone' })
|
||
.expect(400);
|
||
const body = eventPayload();
|
||
const event = save(
|
||
'Create event',
|
||
'POST',
|
||
'/superadmin/music-world/events',
|
||
await adminCall('post', '/events').send(body).expect(201),
|
||
body,
|
||
);
|
||
const filters = '/events/nearby?latitude=24.71&longitude=46.67&radiusKm=2&category=tarab';
|
||
const nearby = save('Nearby events', 'GET', filters, await call('get', filters).expect(200));
|
||
expect(nearby.items[0]).toMatchObject({ id: event.id, distanceKm: 0, canBook: true });
|
||
await call('get', '/events/nearby?latitude=24.71').expect(400);
|
||
const upcoming = await call('get', '/events/upcoming').expect(200);
|
||
expect(upcoming.body.items[0].id).toBe(event.id);
|
||
await call('get', '/events/categories').expect(200);
|
||
await call('put', '/events/' + event.id + '/save').expect(200);
|
||
await call('put', '/events/' + event.id + '/save').expect(200);
|
||
expect((await call('get', '/events/saved').expect(200)).body.total).toBe(1);
|
||
expect((await call('get', '/events/' + event.id, secondStudent).expect(200)).body.isSaved).toBe(
|
||
false,
|
||
);
|
||
await call('delete', '/events/' + event.id + '/save').expect(200);
|
||
await call('get', '/events/' + event.id + '/ticket-categories').expect(200);
|
||
await adminCall('patch', '/events/' + event.id + '/status')
|
||
.send({ status: 'cancelled' })
|
||
.expect(200);
|
||
expect((await call('get', '/events/' + event.id).expect(200)).body.canBook).toBe(false);
|
||
});
|
||
|
||
async function createEventOrder(
|
||
price: number,
|
||
options: { capacity?: number; key: string; token?: string },
|
||
) {
|
||
const { body: event } = await adminCall('post', '/events')
|
||
.send(eventPayload(price, options.capacity))
|
||
.expect(201);
|
||
const route = '/events/' + event.id + '/bookings';
|
||
const selection = { items: [{ ticketCategoryId: event.ticketCategories[0].id, quantity: 1 }] };
|
||
const token = options.token ?? student;
|
||
const quote = save(
|
||
'Event booking preview',
|
||
'POST',
|
||
route + '/preview',
|
||
await call('post', route + '/preview', token)
|
||
.send(selection)
|
||
.expect(200),
|
||
selection,
|
||
);
|
||
const body = { quoteId: quote.quoteId, notes: 'Mobile retry test' };
|
||
const order = save(
|
||
'Reserve event ticket',
|
||
'POST',
|
||
route,
|
||
await call('post', route, token).set('Idempotency-Key', options.key).send(body).expect(201),
|
||
body,
|
||
);
|
||
return { event, selection, route, body, order };
|
||
}
|
||
|
||
it('reserves the last ticket once and permits idempotent requests across connection retries', async () => {
|
||
const { body: event } = await adminCall('post', '/events').send(eventPayload()).expect(201);
|
||
const route = '/events/' + event.id + '/bookings';
|
||
const selection = { items: [{ ticketCategoryId: event.ticketCategories[0].id, quantity: 1 }] };
|
||
const [{ body: a }, { body: b }] = await Promise.all([
|
||
call('post', route + '/preview')
|
||
.send(selection)
|
||
.expect(200),
|
||
call('post', route + '/preview', secondStudent)
|
||
.send(selection)
|
||
.expect(200),
|
||
]);
|
||
const replies = await Promise.all([
|
||
call('post', route).set('Idempotency-Key', 'a-last-ticket').send({ quoteId: a.quoteId }),
|
||
call('post', route, secondStudent)
|
||
.set('Idempotency-Key', 'b-last-ticket')
|
||
.send({ quoteId: b.quoteId }),
|
||
]);
|
||
expect(replies.map((reply) => reply.status).sort()).toEqual([201, 409]);
|
||
const index = replies.findIndex((reply) => reply.status === 201);
|
||
const winner = replies[index].body;
|
||
const token = index ? secondStudent : student;
|
||
const quote = index ? b : a;
|
||
const key = index ? 'b-last-ticket' : 'a-last-ticket';
|
||
expect(
|
||
(
|
||
await call('post', route, token)
|
||
.set('Idempotency-Key', key)
|
||
.send({ quoteId: quote.quoteId })
|
||
.expect(201)
|
||
).body.id,
|
||
).toBe(winner.id);
|
||
await call('post', route, token)
|
||
.set('Idempotency-Key', key)
|
||
.send({ quoteId: quote.quoteId, notes: 'changed' })
|
||
.expect(409);
|
||
await call('get', route + '/' + winner.id, index ? student : secondStudent).expect(404);
|
||
await call('delete', route + '/' + winner.id, token).expect(200);
|
||
expect(
|
||
(await call('get', '/events/' + event.id).expect(200)).body.ticketCategories[0]
|
||
.availableQuantity,
|
||
).toBe(1);
|
||
});
|
||
|
||
it('rejects expired quotes and paid holds without a payment method, and expires holds when the event is cancelled', async () => {
|
||
const { body: event } = await adminCall('post', '/events').send(eventPayload()).expect(201);
|
||
const path = '/events/' + event.id + '/bookings';
|
||
const selection = { items: [{ ticketCategoryId: event.ticketCategories[0].id, quantity: 1 }] };
|
||
const config = app.get(ConfigService);
|
||
config.set('musicWorld.sandboxPayments', false);
|
||
try {
|
||
const unavailable = await call('post', path + '/preview')
|
||
.send(selection)
|
||
.expect(200);
|
||
expect(unavailable.body).toMatchObject({ canBook: false, paymentMethods: [] });
|
||
const denied = await call('post', path)
|
||
.set('Idempotency-Key', 'unpayable')
|
||
.send({ quoteId: unavailable.body.quoteId })
|
||
.expect(422);
|
||
expect(denied.body.code).toBe('PAYMENT_METHOD_UNAVAILABLE');
|
||
} finally {
|
||
config.set('musicWorld.sandboxPayments', true);
|
||
}
|
||
const { body: quote } = await call('post', path + '/preview')
|
||
.send(selection)
|
||
.expect(200);
|
||
await store.quotes.updateOne(
|
||
{ _id: new Types.ObjectId(quote.quoteId) },
|
||
{ $set: { expiresAt: new Date() } },
|
||
);
|
||
const expired = await call('post', path)
|
||
.set('Idempotency-Key', 'expired-quote')
|
||
.send({ quoteId: quote.quoteId })
|
||
.expect(409);
|
||
expect(expired.body.code).toBe('QUOTE_EXPIRED');
|
||
const fresh = await call('post', path + '/preview')
|
||
.send(selection)
|
||
.expect(200);
|
||
const retry = () =>
|
||
call('post', path)
|
||
.set('Idempotency-Key', 'parallel-retry')
|
||
.send({ quoteId: fresh.body.quoteId })
|
||
.expect(201);
|
||
const [first, second] = await Promise.all([retry(), retry()]);
|
||
expect(first.body.id).toBe(second.body.id);
|
||
await adminCall('patch', '/events/' + event.id + '/status')
|
||
.send({ status: 'cancelled' })
|
||
.expect(200);
|
||
expect((await call('get', path + '/' + first.body.id).expect(200)).body.status).toBe('expired');
|
||
expect(
|
||
(await call('get', '/events/' + event.id).expect(200)).body.ticketCategories[0]
|
||
.availableQuantity,
|
||
).toBe(1);
|
||
});
|
||
|
||
it('settles sandbox payments, verifies issued tickets, and releases expired and failed holds', async () => {
|
||
const { event, order, route } = await createEventOrder(900, {
|
||
capacity: 2,
|
||
key: 'sandbox-ticket',
|
||
});
|
||
const methodsUrl = '/payments/methods?kind=event&bookingId=' + order.id;
|
||
const methods = save(
|
||
'Available methods',
|
||
'GET',
|
||
methodsUrl,
|
||
await call('get', methodsUrl).expect(200),
|
||
);
|
||
expect(methods.items).toEqual(
|
||
expect.arrayContaining([
|
||
expect.objectContaining({ id: 'syriatel_cash', available: false }),
|
||
expect.objectContaining({ id: 'sham_cash', available: false }),
|
||
expect.objectContaining({ id: 'sandbox', available: true }),
|
||
]),
|
||
);
|
||
const payment = { kind: 'event', bookingId: order.id, method: 'sandbox' };
|
||
await call('post', '/payments')
|
||
.set('Idempotency-Key', 'unsupported')
|
||
.send({ ...payment, method: 'sham_cash' })
|
||
.expect(422);
|
||
const started = save(
|
||
'Start sandbox payment',
|
||
'POST',
|
||
'/payments',
|
||
await call('post', '/payments')
|
||
.set('Idempotency-Key', 'pay-ticket')
|
||
.send(payment)
|
||
.expect(201),
|
||
payment,
|
||
);
|
||
expect(started.status).toBe('pending');
|
||
expect(
|
||
(
|
||
await call('post', '/payments')
|
||
.set('Idempotency-Key', 'pay-ticket')
|
||
.send(payment)
|
||
.expect(201)
|
||
).body.reference,
|
||
).toBe(started.reference);
|
||
await call('post', '/payments')
|
||
.set('Idempotency-Key', 'different-key')
|
||
.send(payment)
|
||
.expect(409);
|
||
await call('get', '/payments/' + started.id, secondStudent).expect(404);
|
||
await call('post', '/payments/' + started.id + '/simulate', secondStudent)
|
||
.send({ outcome: 'succeeded' })
|
||
.expect(404);
|
||
const sim = '/payments/' + started.id + '/simulate';
|
||
await call('post', sim).send({ outcome: 'pending' }).expect(200);
|
||
const outcomes = await Promise.all([
|
||
call('post', sim).send({ outcome: 'succeeded' }).expect(200),
|
||
call('post', sim).send({ outcome: 'succeeded' }).expect(200),
|
||
]);
|
||
save('Confirm sandbox payment', 'POST', sim, outcomes[0], { outcome: 'succeeded' });
|
||
const confirmed = save(
|
||
'Issued event ticket',
|
||
'GET',
|
||
route + '/' + order.id,
|
||
await call('get', route + '/' + order.id).expect(200),
|
||
);
|
||
expect(confirmed).toMatchObject({
|
||
status: 'confirmed',
|
||
tickets: [expect.objectContaining({ ticketCategoryId: event.ticketCategories[0].id })],
|
||
});
|
||
await adminCall('get', '/tickets/' + confirmed.tickets[0].verificationCode + '/verify').expect(
|
||
200,
|
||
);
|
||
await call('delete', route + '/' + order.id).expect(409);
|
||
await call('get', '/events/bookings').expect(200);
|
||
|
||
for (const outcome of ['failed', 'cancelled', 'expired'] as const) {
|
||
const fixture = await createEventOrder(900, { key: outcome + '-ticket' });
|
||
const attempt = await call('post', '/payments')
|
||
.set('Idempotency-Key', outcome + '-pay')
|
||
.send({ kind: 'event', method: 'sandbox', bookingId: fixture.order.id })
|
||
.expect(201);
|
||
if (outcome === 'expired') {
|
||
await store.bookings.updateOne(
|
||
{ _id: new Types.ObjectId(fixture.order.id) },
|
||
{ $set: { expiresAt: new Date(0) } },
|
||
);
|
||
const expiry = save(
|
||
'Expired payment',
|
||
'GET',
|
||
'/payments/' + attempt.body.id,
|
||
await call('get', '/payments/' + attempt.body.id).expect(200),
|
||
);
|
||
expect(expiry.status).toBe('expired');
|
||
} else {
|
||
const result = await call('post', '/payments/' + attempt.body.id + '/simulate')
|
||
.send({ outcome })
|
||
.expect(200);
|
||
expect(result.body.status).toBe(outcome);
|
||
}
|
||
expect(
|
||
(await call('get', '/events/' + fixture.event.id).expect(200)).body.ticketCategories[0]
|
||
.availableQuantity,
|
||
).toBe(1);
|
||
}
|
||
const free = await createEventOrder(0, { key: 'free-ticket' });
|
||
expect(free.order).toMatchObject({ status: 'confirmed', tickets: [expect.any(Object)] });
|
||
await call('delete', free.route + '/' + free.order.id).expect(200);
|
||
});
|
||
|
||
it('grants protected course access only after payment and synchronizes video, progress and reviews', async () => {
|
||
const teacher = {
|
||
name: 'Oud Teacher',
|
||
yearsExperience: 5,
|
||
linkedUserId: String(secondStudentId),
|
||
};
|
||
const instructor = save(
|
||
'Create linked instructor',
|
||
'POST',
|
||
'/superadmin/music-world/instructors',
|
||
await adminCall('post', '/instructors').send(teacher).expect(201),
|
||
teacher,
|
||
);
|
||
const catalog = {
|
||
title: 'Oud lessons',
|
||
category: 'Oud',
|
||
mode: 'online',
|
||
instructorId: instructor.id,
|
||
priceMinor: 1200,
|
||
currency: 'SAR',
|
||
lessons: [
|
||
{
|
||
title: 'Oud technique',
|
||
durationSeconds: 100,
|
||
objectives: ['Practice'],
|
||
videoKey: 'private-lessons/oud.mp4',
|
||
},
|
||
],
|
||
};
|
||
const course = save(
|
||
'Create online course',
|
||
'POST',
|
||
'/superadmin/music-world/courses',
|
||
await adminCall('post', '/courses').send(catalog).expect(201),
|
||
catalog,
|
||
);
|
||
const route = '/courses/' + course.id;
|
||
await call('get', '/courses?mode=online&q=Oud%20Teacher').expect(200);
|
||
await call('get', '/courses/categories').expect(200);
|
||
await call('put', route + '/save').expect(200);
|
||
expect((await call('get', '/courses/saved').expect(200)).body.total).toBe(1);
|
||
await call('delete', route + '/save').expect(200);
|
||
await call('get', route + '/lessons').expect(403);
|
||
await call('post', route + '/purchases/preview')
|
||
.send({ couponCode: 'BAD' })
|
||
.expect(422);
|
||
await adminCall('post', '/courses/' + course.id + '/coupons')
|
||
.send({ code: 'TEST20', expiresAt: iso(24), percent: 20 })
|
||
.expect(201);
|
||
const quote = save(
|
||
'Discounted course preview',
|
||
'POST',
|
||
route + '/purchases/preview',
|
||
await call('post', route + '/purchases/preview')
|
||
.send({ couponCode: 'test20' })
|
||
.expect(200),
|
||
{ couponCode: 'test20' },
|
||
);
|
||
expect(quote).toMatchObject({ subtotalMinor: 1200, discountMinor: 240, totalMinor: 960 });
|
||
const anotherQuote = await call('post', route + '/purchases/preview')
|
||
.send({})
|
||
.expect(200);
|
||
const purchase = await call('post', route + '/purchases')
|
||
.set('Idempotency-Key', 'buy-oud-course')
|
||
.send({ quoteId: quote.quoteId })
|
||
.expect(201);
|
||
await call('post', route + '/purchases')
|
||
.set('Idempotency-Key', 'second-buy-oud-course')
|
||
.send({ quoteId: anotherQuote.body.quoteId })
|
||
.expect(409);
|
||
const payment = await call('post', '/payments')
|
||
.set('Idempotency-Key', 'pay-oud-course')
|
||
.send({ kind: 'online_course', bookingId: purchase.body.id, method: 'sandbox' })
|
||
.expect(201);
|
||
await call('post', '/payments/' + payment.body.id + '/simulate')
|
||
.send({ outcome: 'succeeded' })
|
||
.expect(200);
|
||
const purchasePath = route + '/purchases/' + purchase.body.id;
|
||
save(
|
||
'Confirmed online course purchase',
|
||
'GET',
|
||
purchasePath,
|
||
await call('get', purchasePath).expect(200),
|
||
);
|
||
expect((await call('get', route + '/access').expect(200)).body.canAccess).toBe(true);
|
||
expect((await call('get', '/courses/mine').expect(200)).body.total).toBe(1);
|
||
const lessons = save(
|
||
'Authorized lessons',
|
||
'GET',
|
||
route + '/lessons',
|
||
await call('get', route + '/lessons').expect(200),
|
||
);
|
||
expect(lessons.items[0]).not.toHaveProperty('videoKey');
|
||
const lessonRoute = route + '/lessons/' + lessons.items[0].id;
|
||
const playback = await call('get', lessonRoute + '/playback').expect(200);
|
||
const url = new URL(playback.body.url);
|
||
const signature = url.searchParams.get('signature')!;
|
||
const redactedPath = playback.body.url.replace(signature, 'REDACTED');
|
||
examples.push({
|
||
name: 'Temporary lesson video',
|
||
method: 'GET',
|
||
path: lessonRoute + '/playback',
|
||
status: 200,
|
||
response: { ...playback.body, url: redactedPath },
|
||
});
|
||
await server()
|
||
.get(url.pathname + url.search)
|
||
.set('Authorization', 'Bearer ' + secondStudent)
|
||
.set('Range', 'bytes=0-15')
|
||
.expect(403);
|
||
await server()
|
||
.get(url.pathname + url.search)
|
||
.set('Authorization', 'Bearer ' + student)
|
||
.set('Range', 'bytes=0-15')
|
||
.expect('Content-Range', 'bytes 0-15/256')
|
||
.expect(206);
|
||
await server()
|
||
.get(url.pathname + url.search)
|
||
.set('Authorization', 'Bearer ' + student)
|
||
.set('Range', 'bytes=300-400')
|
||
.expect(416);
|
||
await call('get', lessonRoute + '/video?expires=1&signature=' + signature).expect(403);
|
||
const rating = { courseRating: 5, instructorRating: 4, comment: 'Good' };
|
||
await call('put', route + '/review')
|
||
.send(rating)
|
||
.expect(403);
|
||
await call('put', lessonRoute + '/progress')
|
||
.send({ positionSeconds: 101, revision: 0 })
|
||
.expect(400);
|
||
await call('put', lessonRoute + '/progress')
|
||
.send({ positionSeconds: 90, revision: 0 })
|
||
.expect(200);
|
||
await call('put', lessonRoute + '/progress')
|
||
.send({ positionSeconds: 30, revision: 0 })
|
||
.expect(409);
|
||
await call('put', lessonRoute + '/progress')
|
||
.send({ positionSeconds: 30, revision: 1 })
|
||
.expect(200);
|
||
const progress = save(
|
||
'Course progress',
|
||
'GET',
|
||
route + '/progress',
|
||
await call('get', route + '/progress').expect(200),
|
||
);
|
||
expect(progress).toMatchObject({
|
||
progressPercentage: 100,
|
||
items: [expect.objectContaining({ positionSeconds: 30, completed: true })],
|
||
});
|
||
save(
|
||
'Student review',
|
||
'PUT',
|
||
route + '/review',
|
||
await call('put', route + '/review')
|
||
.send(rating)
|
||
.expect(200),
|
||
rating,
|
||
);
|
||
await call('put', route + '/review')
|
||
.send({ courseRating: 4, instructorRating: 5 })
|
||
.expect(200);
|
||
const instructorView = save(
|
||
'Instructor details',
|
||
'GET',
|
||
'/instructors/' + instructor.id,
|
||
await call('get', '/instructors/' + instructor.id).expect(200),
|
||
);
|
||
expect(instructorView).toMatchObject({
|
||
studentsCount: 1,
|
||
coursesCount: 1,
|
||
rating: 5,
|
||
reviewsCount: 1,
|
||
});
|
||
expect((await call('get', route).expect(200)).body).toMatchObject({
|
||
rating: 4,
|
||
reviewsCount: 1,
|
||
});
|
||
await call('get', '/instructors/' + instructor.id + '/courses').expect(200);
|
||
});
|
||
|
||
it('limits seat reservations and allows only an administrator to verify payment at the institute', async () => {
|
||
const teacher = await adminCall('post', '/instructors')
|
||
.send({ name: 'Center Teacher' })
|
||
.expect(201);
|
||
const institute = save(
|
||
'Institute with location',
|
||
'POST',
|
||
'/superadmin/music-world/institutes',
|
||
await adminCall('post', '/institutes')
|
||
.send({
|
||
title: 'Oud Institute',
|
||
place: { location: 'Riyadh', latitude: 24.7, longitude: 46.7 },
|
||
})
|
||
.expect(201),
|
||
);
|
||
const course = await adminCall('post', '/courses')
|
||
.send({
|
||
title: 'Group instruction',
|
||
category: 'Oud',
|
||
mode: 'in_person',
|
||
instructorId: teacher.body.id,
|
||
instituteId: institute.id,
|
||
priceMinor: 2500,
|
||
currency: 'SAR',
|
||
})
|
||
.expect(201);
|
||
const route = '/courses/' + course.body.id;
|
||
const offering = await adminCall('post', route + '/offerings')
|
||
.send({
|
||
instituteId: institute.id,
|
||
...schedule(),
|
||
...sale(),
|
||
priceMinor: 2500,
|
||
capacity: 1,
|
||
maxPerBooking: 1,
|
||
schedule: ['Saturday 10:00–12:00'],
|
||
payAtCenter: true,
|
||
})
|
||
.expect(201);
|
||
save(
|
||
'Scheduled course offerings',
|
||
'GET',
|
||
route + '/offerings',
|
||
await call('get', route + '/offerings').expect(200),
|
||
);
|
||
await call('get', '/institutes/' + institute.id + '/courses').expect(200);
|
||
const path = route + '/bookings';
|
||
const selection = { offeringId: offering.body.id, quantity: 1 };
|
||
const quotes = await Promise.all([
|
||
call('post', path + '/preview')
|
||
.send(selection)
|
||
.expect(200),
|
||
call('post', path + '/preview', secondStudent)
|
||
.send(selection)
|
||
.expect(200),
|
||
]);
|
||
const booking = await call('post', path)
|
||
.set('Idempotency-Key', 'reserve-seat')
|
||
.send({ quoteId: quotes[0].body.quoteId })
|
||
.expect(201);
|
||
await call('post', path, secondStudent)
|
||
.set('Idempotency-Key', 'reserve-same-seat')
|
||
.send({ quoteId: quotes[1].body.quoteId })
|
||
.expect(409);
|
||
const attempt = await call('post', '/payments')
|
||
.set('Idempotency-Key', 'pay-center')
|
||
.send({ kind: 'in_person_course', bookingId: booking.body.id, method: 'pay_at_center' })
|
||
.expect(201);
|
||
await call('post', '/payments/' + attempt.body.id + '/simulate')
|
||
.send({ outcome: 'succeeded' })
|
||
.expect(404);
|
||
await adminCall('post', '/payments/' + attempt.body.id + '/verify-at-center').expect(200);
|
||
const confirmed = save(
|
||
'Confirmed in-person booking',
|
||
'GET',
|
||
path + '/' + booking.body.id,
|
||
await call('get', path + '/' + booking.body.id).expect(200),
|
||
);
|
||
expect(confirmed).toMatchObject({ status: 'confirmed', enrollmentId: expect.any(String) });
|
||
expect((await call('get', route + '/review').expect(200)).body.eligible).toBe(false);
|
||
});
|
||
|
||
it('uses viewer-safe talent counters and returns independently paged ranked discovery results', async () => {
|
||
const hidden = new Types.ObjectId();
|
||
const blocked = new Types.ObjectId();
|
||
await database.collection('users').insertMany([
|
||
{
|
||
_id: hidden,
|
||
email: 'hidden@example.invalid',
|
||
username: 'private_talent',
|
||
name: 'Oud Private',
|
||
role: 'user',
|
||
isDisabled: false,
|
||
isPrivate: true,
|
||
musicRoles: ['composer'],
|
||
},
|
||
{
|
||
_id: blocked,
|
||
email: 'blocked@example.invalid',
|
||
username: 'blocked_talent',
|
||
name: 'Oud Blocked',
|
||
role: 'user',
|
||
isDisabled: false,
|
||
isPrivate: false,
|
||
musicRoles: ['composer'],
|
||
},
|
||
]);
|
||
await database.collection('blocks').insertOne({ blockerId: blocked, blockedId: studentId });
|
||
await database.collection('posts').insertMany([
|
||
{
|
||
authorId: secondStudentId,
|
||
visibility: 'public',
|
||
postType: 'audio',
|
||
playCount: 8,
|
||
content: 'Oud',
|
||
hashtags: ['oud'],
|
||
createdAt: new Date(),
|
||
},
|
||
{
|
||
authorId: secondStudentId,
|
||
visibility: 'private',
|
||
postType: 'video',
|
||
playCount: 90,
|
||
content: 'Oud private',
|
||
createdAt: new Date(),
|
||
},
|
||
{
|
||
authorId: studentId,
|
||
visibility: 'public',
|
||
postType: 'text',
|
||
collaboratorIds: [secondStudentId],
|
||
content: 'An oud piece',
|
||
createdAt: new Date(),
|
||
},
|
||
{
|
||
authorId: blocked,
|
||
visibility: 'public',
|
||
postType: 'text',
|
||
collaboratorIds: [secondStudentId],
|
||
content: 'Oud blocked',
|
||
createdAt: new Date(),
|
||
},
|
||
]);
|
||
const discovery = '/users/discover?q=Oud&hasAvatarOnly=false';
|
||
const talents = save(
|
||
'Talent counters and role buckets',
|
||
'GET',
|
||
discovery,
|
||
await call('get', discovery).expect(200),
|
||
);
|
||
expect(talents.items.map((item: { _id: string }) => item._id)).toEqual([
|
||
String(secondStudentId),
|
||
String(studentId),
|
||
]);
|
||
expect(talents.items[0]).toMatchObject({ listenCount: 8, collaborationsCount: 1 });
|
||
expect(talents.roleBuckets.find((row: { role: string }) => row.role === 'composer').count).toBe(
|
||
2,
|
||
);
|
||
const opportunity = {
|
||
title: 'Oud ensemble rehearsal',
|
||
category: 'Oud',
|
||
linkedUserId: String(secondStudentId),
|
||
closesAt: iso(24),
|
||
};
|
||
await adminCall('post', '/opportunities').send(opportunity).expect(201);
|
||
const path =
|
||
'/discovery/search?q=Oud&type=users,posts,hashtags,courses,lessons,opportunities&pages=users:2&limit=1&appVersion=1.2.0';
|
||
const results = save(
|
||
'Unified search with independent pages',
|
||
'GET',
|
||
path,
|
||
await call('get', path).expect(200),
|
||
);
|
||
expect(results.groups.users.page).toBe(2);
|
||
expect(results.groups.posts.items[0].content).toBe('Oud');
|
||
expect(results.groups.hashtags.items[0].tag).toBe('oud');
|
||
expect(results.groups.lessons.items[0]).not.toHaveProperty('videoKey');
|
||
expect(results.groups.opportunities.total).toBe(1);
|
||
const all = await call('get', '/discovery/search?q=Oud&type=all&appVersion=1.2.0').expect(200);
|
||
expect(Object.keys(all.body.groups)).toHaveLength(14);
|
||
const features = await server().get('/api/v1/discovery/features?appVersion=1.1.0').expect(200);
|
||
expect(
|
||
features.body.results.find((item: { type: string }) => item.type === 'courses').enabled,
|
||
).toBe(false);
|
||
expect(
|
||
(await call('get', '/discovery/search?q=Oud&type=courses&appVersion=1.1.0').expect(200)).body
|
||
.unavailableTypes,
|
||
).toEqual(['courses']);
|
||
const emptyPath = '/discovery/search?q=zzzznoresults&type=events';
|
||
const empty = save('Empty results', 'GET', emptyPath, await call('get', emptyPath).expect(200));
|
||
expect(empty.groups.events.items).toEqual([]);
|
||
const badPath = '/discovery/search?q=Oud&type=bad';
|
||
save(
|
||
'Unsupported discovery result type',
|
||
'GET',
|
||
badPath,
|
||
await call('get', badPath).expect(400),
|
||
);
|
||
await call('get', '/discovery/search?q=Oud&pages=posts:0').expect(400);
|
||
const arabic = await call(
|
||
'get',
|
||
'/discovery/search?q=' + encodeURIComponent('عُود') + '&type=events',
|
||
).expect(200);
|
||
expect(arabic.body.groups.events.total).toBeGreaterThan(0);
|
||
expect((await call('get', '/search?q=oud').expect(200)).body.type).toBe('all');
|
||
});
|
||
});
|