Files
back_end_oudelaa/test/marketplace-commerce.e2e-spec.ts

506 lines
21 KiB
TypeScript

import { INestApplication, UnauthorizedException, ValidationPipe } from '@nestjs/common';
import { Test } from '@nestjs/testing';
import { MongooseModule, getModelToken } from '@nestjs/mongoose';
import { spawn, ChildProcess } from 'child_process';
import { mkdtempSync, writeFileSync } from 'fs';
import { tmpdir } from 'os';
import { join } from 'path';
import { createServer } from 'net';
import { createConnection, Model, Types } from 'mongoose';
import * as request from 'supertest';
import { OrdersModule } from '../src/modules/orders/orders.module';
import { Order } from '../src/modules/orders/schemas/order.schema';
import { Instrument, InstrumentSchema } from '../src/modules/marketplace/schemas/instrument.schema';
import {
RepairShop,
RepairShopSchema,
} from '../src/modules/marketplace/schemas/repair-shop.schema';
import { User, UserSchema } from '../src/modules/users/schemas/user.schema';
import { MarketplaceController } from '../src/modules/marketplace/marketplace.controller';
import { MarketplaceService } from '../src/modules/marketplace/marketplace.service';
import { MarketplaceRepository } from '../src/modules/marketplace/marketplace.repository';
import { UsersRepository } from '../src/modules/users/users.repository';
import { ManagedStorageService } from '../src/infrastructure/storage/managed-storage.service';
import { AuditService } from '../src/modules/audit/audit.service';
import { SuperAdminCase } from '../src/modules/superadmin/schemas/superadmin-case.schema';
import { JwtAuthGuard } from '../src/common/guards/jwt-auth.guard';
import { RolesGuard } from '../src/common/guards/roles.guard';
import { SuperAdminJwtAuthGuard } from '../src/common/guards/super-admin-jwt-auth.guard';
import { SuperAdminPermissionsGuard } from '../src/common/guards/superadmin-permissions.guard';
// Opt-in: starts a private mongod replica set; never connects to an application database.
const integration = process.env.MARKETPLACE_INTEGRATION === '1' ? describe : describe.skip;
integration('Marketplace HTTP + MongoDB transactions', () => {
jest.setTimeout(120000);
let app: INestApplication;
let mongo: ChildProcess;
let listings: Model<any>;
let users: Model<any>;
let orders: Model<any>;
const buyer = new Types.ObjectId().toString();
const stranger = new Types.ObjectId().toString();
const shopId = new Types.ObjectId().toString();
const listingId = new Types.ObjectId().toString();
const secondId = new Types.ObjectId().toString();
const examples: any[] = [];
const checkout = { items: [{ listingId, quantity: 2 }], fulfillmentMethod: 'delivery' };
const orderBody = {
...checkout,
customerName: 'Flutter Test Customer',
customerPhone: '+966500000000',
city: 'Riyadh',
address: 'Test street 10',
latitude: 24.7136,
longitude: 46.6753,
paymentMethod: 'cash_on_delivery',
notes: 'Call before arrival',
};
async function call(method: string, path: string, body?: object, as = buyer) {
let req = (request(app.getHttpServer()) as any)[method](`/api/v1${path}`);
if (as) req = req.set('Authorization', `Bearer ${as}`);
return body ? req.send(body) : req;
}
async function capture(name: string, method: string, path: string, body?: object) {
const response = await call(method, path, body);
expect(response.status).toBe(method === 'post' ? 201 : 200);
examples.push({
name,
method: method.toUpperCase(),
path,
request: body,
status: response.status,
response: response.body,
});
return response.body;
}
beforeAll(async () => {
const server = createServer();
await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve));
const port = (server.address() as { port: number }).port;
await new Promise<void>((resolve, reject) =>
server.close((error) => (error ? reject(error) : resolve())),
);
const directory = mkdtempSync(join(tmpdir(), 'oudelaa-marketplace-test-'));
const executable = process.env.MONGOD_BINARY ?? 'mongod';
mongo = spawn(
executable,
[
'--dbpath',
directory,
'--port',
String(port),
'--bind_ip',
'127.0.0.1',
'--replSet',
'marketplaceTest',
'--logpath',
join(directory, 'mongo.log'),
],
{ windowsHide: true, stdio: 'ignore' },
);
let spawnError: Error | undefined;
mongo.on('error', (error) => {
spawnError = error;
});
const uri = `mongodb://127.0.0.1:${port}/marketplace_test`;
const bootstrap = createConnection(`${uri}?directConnection=true`, {
serverSelectionTimeoutMS: 30000,
});
await bootstrap.asPromise();
if (spawnError) throw spawnError;
await bootstrap
.db!.admin()
.command({
replSetInitiate: {
_id: 'marketplaceTest',
members: [{ _id: 0, host: `127.0.0.1:${port}` }],
},
});
await bootstrap.close();
const guard = {
canActivate(context: any) {
const req = context.switchToHttp().getRequest();
const token = req.headers.authorization?.replace('Bearer ', '');
if (!token || !Types.ObjectId.isValid(token)) throw new UnauthorizedException();
req.user = { sub: token, role: token === shopId ? 'admin' : 'user' };
return true;
},
};
const module = await Test.createTestingModule({
imports: [
MongooseModule.forRoot(`${uri}?replicaSet=marketplaceTest`),
OrdersModule,
MongooseModule.forFeature([
{ name: User.name, schema: UserSchema },
{ name: Instrument.name, schema: InstrumentSchema },
{ name: RepairShop.name, schema: RepairShopSchema },
]),
],
controllers: [MarketplaceController],
providers: [
MarketplaceService,
MarketplaceRepository,
UsersRepository,
{ provide: ManagedStorageService, useValue: {} },
{ provide: AuditService, useValue: {} },
{ provide: getModelToken(SuperAdminCase.name), useValue: {} },
],
})
.overrideGuard(JwtAuthGuard)
.useValue(guard)
.overrideGuard(SuperAdminJwtAuthGuard)
.useValue(guard)
.overrideGuard(RolesGuard)
.useValue({ canActivate: () => true })
.overrideGuard(SuperAdminPermissionsGuard)
.useValue({ canActivate: () => true })
.compile();
app = module.createNestApplication();
app.useLogger(false);
app.setGlobalPrefix('api/v1');
app.useGlobalPipes(
new ValidationPipe({
whitelist: true,
forbidNonWhitelisted: true,
transform: true,
transformOptions: { enableImplicitConversion: true },
}),
);
await app.init();
listings = module.get(getModelToken(Instrument.name));
users = module.get(getModelToken(User.name));
orders = module.get(getModelToken(Order.name));
await Promise.all([listings.init(), users.init(), orders.init()]);
await users.collection.insertOne({
_id: new Types.ObjectId(shopId),
name: 'Test Store Owner',
email: 'store@example.com',
username: 'test_store',
role: 'admin',
isDisabled: false,
shopName: 'Oudelaa Test Store',
shopDescription: 'Musical instruments and accessories',
shopImageUrls: ['https://example.com/shop-logo.jpg', 'https://example.com/shop-cover.jpg'],
shopLocation: 'Riyadh, Test Street',
shopLatitude: 24.7136,
shopLongitude: 46.6753,
shopPhone: '+966500000000',
isVerified: true,
shopDeliveryAvailable: true,
shopDeliveryFee: 25,
shopTrialPolicy: 'Trial in store',
shopReturnPolicy: 'Returns within 7 days',
shopPolicies: 'Contact the store before returns',
});
await listings.create([
{
_id: listingId,
ownerAdminId: shopId,
title: 'Professional Oud',
description: 'Test instrument',
price: 1250.25,
quantity: 10,
imageUrls: ['https://example.com/oud-front.jpg', 'https://example.com/oud-back.jpg'],
condition: 'new',
instrumentType: 'Oud',
},
{ _id: secondId, ownerAdminId: shopId, title: 'Strings', price: 20, quantity: 3 },
]);
});
afterAll(async () => {
if (process.env.MARKETPLACE_CAPTURE_EXAMPLES === '1' && examples.length) {
writeFileSync(
'postman/marketplace-response-examples.json',
JSON.stringify(
{
source:
'Captured HTTP responses using real controllers, services and a private MongoDB replica set. Test authentication guard; synthetic fixtures. No response envelope.',
capturedAt: new Date().toISOString(),
examples,
},
null,
2,
) + '\n',
);
}
if (app) await app.close();
if (mongo && mongo.exitCode === null) {
const exited = new Promise<void>((resolve) => mongo.once('exit', () => resolve()));
mongo.kill();
await exited;
}
});
it('captures product, shop, cart, checkout and order responses through HTTP', async () => {
const listing = await capture('Product details', 'get', `/marketplace/listings/${listingId}`);
expect(listing).toMatchObject({
id: listingId,
stockQuantity: 10,
isInStock: true,
shopId,
deliveryAvailable: true,
deliveryFee: 25,
});
expect(listing.shop).toMatchObject({
phone: '+966500000000',
isVerified: true,
latitude: 24.7136,
});
expect(listing.imageUrls).toHaveLength(2);
const home = await capture('Marketplace home', 'get', '/marketplace/home?listingsLimit=5&instrumentsLimit=5&repairShopsLimit=5');
expect(home.summary.activeListings).toBe(2);
expect(home.sections.listings.total).toBe(2);
await capture('Shop details', 'get', `/marketplace/shops/${shopId}`);
const filtered = await capture(
'Filter listings by shopId',
'get',
`/marketplace/listings?shopId=${shopId}`,
);
expect(filtered.total).toBe(2);
await capture('Shop listings', 'get', `/marketplace/shops/${shopId}/listings`);
await capture('Empty cart', 'get', '/marketplace/cart');
const cart = await capture('Set cart item quantity', 'post', '/marketplace/cart/items', {
listingId,
quantity: 2,
});
await capture('Get cart', 'get', '/marketplace/cart');
await capture(
'Update cart item quantity',
'patch',
`/marketplace/cart/items/${cart.items[0].id}`,
{ quantity: 3 },
);
await capture('Remove cart item', 'delete', `/marketplace/cart/items/${cart.items[0].id}`);
await call('post', '/marketplace/cart/items', { listingId, quantity: 1 });
await capture('Clear cart', 'delete', '/marketplace/cart');
const preview = await capture(
'Checkout preview',
'post',
'/marketplace/checkout/preview',
checkout,
);
expect(preview).toMatchObject({
subtotal: 2500.5,
deliveryFee: 25,
discount: 0,
total: 2525.5,
currency: 'SAR',
isValid: true,
});
const order = await capture('Create order', 'post', '/marketplace/orders', orderBody);
expect(order.total).toBe(preview.total);
expect((await listings.findById(listingId)).quantity).toBe(8);
await capture('List my orders', 'get', '/marketplace/orders');
await capture('Get order', 'get', `/marketplace/orders/${order.id}`);
await capture('Cancel order', 'post', `/marketplace/orders/${order.id}/cancel`, {
reason: 'Changed my mind',
});
expect((await listings.findById(listingId)).quantity).toBe(10);
expect((await call('post', `/marketplace/orders/${order.id}/cancel`, {})).status).toBe(409);
expect((await listings.findById(listingId)).quantity).toBe(10);
});
it('keeps public pagination and home counts consistent for legacy, inactive, disabled and missing owners', async () => {
const hiddenOwner = new Types.ObjectId();
const extraIds = Array.from({ length: 6 }, () => new Types.ObjectId());
const repairIds = [new Types.ObjectId(), new Types.ObjectId()];
const repairs = app.get<Model<any>>(getModelToken(RepairShop.name));
await users.collection.insertOne({ _id: hiddenOwner, name: 'Hidden', username: `hidden_${hiddenOwner}`, email: `hidden_${hiddenOwner}@example.com`, role: 'admin', isDisabled: true });
await listings.collection.insertMany(extraIds.map((_id, index) => ({
_id, ownerAdminId: index === 4 ? hiddenOwner : index === 5 ? new Types.ObjectId() : new Types.ObjectId(shopId),
title: `Perf fixture ${index}`, price: index + 1, currency: 'SAR', quantity: 1,
isActive: index !== 3, createdAt: new Date(1700000000000 + index),
...(index === 1 ? {} : { listingCategory: index === 2 ? null : 'accessory' }),
})));
await repairs.collection.insertMany(repairIds.map((_id, index) => ({ _id, ownerAdminId: index ? hiddenOwner : new Types.ObjectId(shopId), name: 'Test repair', isActive: true, createdAt: new Date() })));
try {
const active = await call('get', '/marketplace/home?listingsLimit=1&instrumentsLimit=1&repairShopsLimit=1');
expect(active.status).toBe(200);
expect(active.body.summary).toEqual({ activeListings: 5, activeMusicalInstruments: 4, activeRepairShops: 1 });
expect(active.body.sections.listings).toMatchObject({ total: 5, count: 1, pagination: { hasNextPage: true } });
expect(active.body.sections.musicalInstruments.total).toBe(4);
expect(active.body.filters.listingCategories).toContainEqual({ key: 'musical_instrument', count: 2 });
expect(active.body.filters.listingCategories).toContainEqual({ key: 'accessory', count: 1 });
const all = await call('get', '/marketplace/home?onlyActive=false&listingsLimit=20');
expect(all.body.summary.activeListings).toBe(6);
expect(all.body.sections.listings.total).toBe(6);
expect(all.body.sections.listings.items.some((item: any) => item.isActive === false)).toBe(true);
const page = await call('get', '/marketplace/listings?limit=2&page=2&sortBy=price&sortOrder=asc');
expect(page.status).toBe(200);
expect(page.body.total).toBe(5);
expect(page.body.items.map((item: any) => item.price)).toEqual([3, 20]);
const empty = await call('get', '/marketplace/listings?limit=2&page=99');
expect(empty.body).toMatchObject({ items: [], total: 5, count: 0 });
const repairPage = await call('get', '/marketplace/repair-shops?limit=1');
expect(repairPage.body.total).toBe(1);
expect(repairPage.body.items).toHaveLength(1);
await request(app.getHttpServer()).get('/api/v1/marketplace/home?listingsLimit=1.5').expect(400);
await request(app.getHttpServer()).get('/api/v1/marketplace/listings?limit=1.5').expect(400);
await request(app.getHttpServer()).get(`/api/v1/marketplace/listings?q=${'x'.repeat(121)}`).expect(400);
} finally {
await listings.collection.deleteMany({ _id: { $in: extraIds } });
await repairs.collection.deleteMany({ _id: { $in: repairIds } });
await users.collection.deleteOne({ _id: hiddenOwner });
}
});
it('rejects invalid quantities, duplicate lines, missing delivery details and electronic payment', async () => {
for (const body of [
{ ...orderBody, items: [{ listingId, quantity: 0 }] },
{ ...orderBody, items: [{ listingId, quantity: 1.5 }] },
{ ...orderBody, items: [checkout.items[0], checkout.items[0]] },
{ ...orderBody, address: '' },
{ ...orderBody, latitude: 91 },
{ ...orderBody, longitude: undefined },
{ ...orderBody, paymentMethod: 'card' },
{ ...orderBody, total: 1 },
{ ...orderBody, customerName: ' ' },
]) {
expect((await call('post', '/marketplace/orders', body)).status).toBe(400);
}
expect((await call('get', '/marketplace/listings?shopId=invalid')).status).toBe(400);
expect((await call('get', '/marketplace/shops/invalid/listings')).status).toBe(400);
expect((await call('get', '/marketplace/cart', undefined, '')).status).toBe(401);
});
it('enforces cart and order ownership', async () => {
const cart = await call('post', '/marketplace/cart/items', { listingId, quantity: 1 });
const itemId = cart.body.items[0].id;
expect(
(await call('patch', `/marketplace/cart/items/${itemId}`, { quantity: 2 }, stranger)).status,
).toBe(404);
expect(
(await call('delete', `/marketplace/cart/items/${itemId}`, undefined, stranger)).status,
).toBe(404);
const order = await call('post', '/marketplace/orders', orderBody);
expect(
(await call('get', `/marketplace/orders/${order.body.id}`, undefined, stranger)).status,
).toBe(404);
expect(
(await call('post', `/marketplace/orders/${order.body.id}/cancel`, {}, stranger)).status,
).toBe(409);
await call('post', `/marketplace/orders/${order.body.id}/cancel`, {});
});
it('reports insufficient stock and rejects mixed shops, currencies and unavailable delivery', async () => {
const preview = await capture(
'Preview insufficient stock',
'post',
'/marketplace/checkout/preview',
{ ...checkout, items: [{ listingId, quantity: 100 }] },
);
expect(preview.isValid).toBe(false);
expect(
(
await call('post', '/marketplace/orders', {
...orderBody,
items: [{ listingId, quantity: 100 }],
})
).status,
).toBe(409);
await listings.updateOne({ _id: secondId }, { currency: 'USD' });
const multi = {
...checkout,
items: [
{ listingId, quantity: 1 },
{ listingId: secondId, quantity: 1 },
],
};
expect((await call('post', '/marketplace/checkout/preview', multi)).status).toBe(400);
await listings.updateOne({ _id: secondId }, { currency: 'SAR' });
await users.collection.insertOne({
_id: new Types.ObjectId(stranger),
email: 'second@example.com',
username: 'second_store',
role: 'admin',
isDisabled: false,
});
await listings.updateOne({ _id: secondId }, { ownerAdminId: stranger });
expect((await call('post', '/marketplace/checkout/preview', multi)).status).toBe(400);
await listings.updateOne({ _id: secondId }, { ownerAdminId: shopId });
await users.updateOne({ _id: shopId }, { shopDeliveryAvailable: false });
expect((await call('post', '/marketplace/checkout/preview', checkout)).status).toBe(400);
const pickup = await call('post', '/marketplace/checkout/preview', {
...checkout,
fulfillmentMethod: 'pickup',
});
expect(pickup.body.deliveryFee).toBe(0);
await users.updateOne({ _id: shopId }, { shopDeliveryAvailable: true, isDisabled: true });
expect((await call('post', '/marketplace/orders', orderBody)).status).toBe(400);
await users.updateOne({ _id: shopId }, { isDisabled: false });
});
it('prevents overselling under concurrent checkout and restores all lines exactly once', async () => {
await listings.updateOne({ _id: listingId }, { quantity: 1 });
const body = {
...orderBody,
items: [
{ listingId, quantity: 1 },
{ listingId: secondId, quantity: 1 },
],
};
const responses = await Promise.all([
call('post', '/marketplace/orders', body),
call('post', '/marketplace/orders', body),
]);
expect(responses.map((r) => r.status).sort()).toEqual([201, 409]);
expect((await listings.findById(listingId)).quantity).toBe(0);
expect((await listings.findById(secondId)).quantity).toBe(2);
const orderId = responses.find((r) => r.status === 201)!.body.id;
const cancellations = await Promise.all([
call('post', `/marketplace/orders/${orderId}/cancel`, {}),
call('post', `/marketplace/orders/${orderId}/cancel`, {}),
]);
expect(cancellations.map((r) => r.status).sort()).toEqual([201, 409]);
expect((await listings.findById(listingId)).quantity).toBe(1);
expect((await listings.findById(secondId)).quantity).toBe(3);
});
it('rolls back stock when persisting an order fails', async () => {
const before = (await listings.findById(listingId)).quantity;
const create = jest
.spyOn(orders, 'create')
.mockRejectedValueOnce(new Error('Simulated database write failure') as never);
try {
expect(
(
await call('post', '/marketplace/orders', {
...orderBody,
items: [{ listingId, quantity: 1 }],
})
).status,
).toBe(500);
expect((await listings.findById(listingId)).quantity).toBe(before);
} finally {
create.mockRestore();
}
});
it('company cancellation restores every line and blocks buyer cancellation after processing', async () => {
const body = {
...orderBody,
items: [
{ listingId, quantity: 1 },
{ listingId: secondId, quantity: 1 },
],
};
const created = await call('post', '/marketplace/orders', body);
const id = created.body.id;
expect(
(await call('patch', `/orders/admin/${id}/status`, { status: 'confirmed' }, shopId)).status,
).toBe(200);
expect(
(await call('patch', `/orders/admin/${id}/status`, { status: 'processing' }, shopId)).status,
).toBe(200);
expect((await call('post', `/marketplace/orders/${id}/cancel`, {})).status).toBe(409);
expect(
(await call('patch', `/orders/admin/${id}/status`, { status: 'cancelled' }, shopId)).status,
).toBe(200);
expect((await listings.findById(listingId)).quantity).toBe(1);
expect((await listings.findById(secondId)).quantity).toBe(3);
});
});