224 lines
8.0 KiB
TypeScript
224 lines
8.0 KiB
TypeScript
import { INestApplication, ValidationPipe } from '@nestjs/common';
|
|
import { Test, TestingModule } from '@nestjs/testing';
|
|
import { ConfigModule, ConfigService } from '@nestjs/config';
|
|
import { TypeOrmModule } from '@nestjs/typeorm';
|
|
import { JwtModule, JwtService } from '@nestjs/jwt';
|
|
import * as request from 'supertest';
|
|
import { DataSource } from 'typeorm';
|
|
import * as bcrypt from 'bcrypt';
|
|
|
|
import { AuthModule } from '../src/modules/auth/auth.module';
|
|
import { UsersModule } from '../src/modules/users/users.module';
|
|
import { CreditsModule } from '../src/modules/credits/credits.module';
|
|
import { User } from '../src/modules/users/entities/user.entity';
|
|
import { Otp } from '../src/modules/auth/entities/otp.entity';
|
|
import { RefreshToken } from '../src/modules/auth/entities/refresh-token.entity';
|
|
import { CreditBalance } from '../src/modules/credits/entities/credit-balance.entity';
|
|
import { CreditTransaction, TransactionType } from '../src/modules/credits/entities/credit-transaction.entity';
|
|
import { CreditPackage } from '../src/modules/credits/entities/credit-package.entity';
|
|
|
|
describe('CreditsController (e2e)', () => {
|
|
let app: INestApplication;
|
|
let dataSource: DataSource;
|
|
let jwtService: JwtService;
|
|
let accessToken: string;
|
|
let userId: string;
|
|
|
|
beforeAll(async () => {
|
|
const moduleFixture: TestingModule = await Test.createTestingModule({
|
|
imports: [
|
|
ConfigModule.forRoot({
|
|
isGlobal: true,
|
|
}),
|
|
TypeOrmModule.forRootAsync({
|
|
imports: [ConfigModule],
|
|
useFactory: () => ({
|
|
type: 'postgres',
|
|
host: process.env.DATABASE_HOST || 'localhost',
|
|
port: parseInt(process.env.DATABASE_PORT || '5433'),
|
|
username: process.env.DATABASE_USER || 'postgres',
|
|
password: process.env.DATABASE_PASSWORD || 'postgres',
|
|
database: process.env.DATABASE_NAME || 'miinventario_test',
|
|
entities: [User, Otp, RefreshToken, CreditBalance, CreditTransaction, CreditPackage],
|
|
synchronize: true,
|
|
dropSchema: true,
|
|
}),
|
|
inject: [ConfigService],
|
|
}),
|
|
JwtModule.register({
|
|
secret: 'test-secret',
|
|
signOptions: { expiresIn: '15m' },
|
|
}),
|
|
AuthModule,
|
|
UsersModule,
|
|
CreditsModule,
|
|
],
|
|
})
|
|
.overrideProvider(ConfigService)
|
|
.useValue({
|
|
get: (key: string, defaultValue?: any) => {
|
|
const config: Record<string, any> = {
|
|
NODE_ENV: 'development',
|
|
DATABASE_HOST: process.env.DATABASE_HOST || 'localhost',
|
|
DATABASE_PORT: parseInt(process.env.DATABASE_PORT || '5433'),
|
|
DATABASE_NAME: process.env.DATABASE_NAME || 'miinventario_test',
|
|
DATABASE_USER: process.env.DATABASE_USER || 'postgres',
|
|
DATABASE_PASSWORD: process.env.DATABASE_PASSWORD || 'postgres',
|
|
JWT_SECRET: 'test-secret',
|
|
JWT_EXPIRES_IN: '15m',
|
|
JWT_REFRESH_SECRET: 'test-refresh-secret',
|
|
JWT_REFRESH_EXPIRES_IN: '7d',
|
|
};
|
|
return config[key] ?? defaultValue;
|
|
},
|
|
})
|
|
.compile();
|
|
|
|
app = moduleFixture.createNestApplication();
|
|
app.useGlobalPipes(
|
|
new ValidationPipe({
|
|
whitelist: true,
|
|
forbidNonWhitelisted: true,
|
|
transform: true,
|
|
}),
|
|
);
|
|
|
|
await app.init();
|
|
dataSource = moduleFixture.get<DataSource>(DataSource);
|
|
jwtService = moduleFixture.get<JwtService>(JwtService);
|
|
});
|
|
|
|
afterAll(async () => {
|
|
if (dataSource?.isInitialized) {
|
|
await dataSource.destroy();
|
|
}
|
|
await app.close();
|
|
});
|
|
|
|
beforeEach(async () => {
|
|
// Clean up
|
|
await dataSource.query('DELETE FROM credit_transactions');
|
|
await dataSource.query('DELETE FROM credit_packages');
|
|
await dataSource.query('DELETE FROM credit_balances');
|
|
await dataSource.query('DELETE FROM refresh_tokens');
|
|
await dataSource.query('DELETE FROM otps');
|
|
await dataSource.query('DELETE FROM users');
|
|
|
|
// Create test user
|
|
const passwordHash = await bcrypt.hash('testpassword123', 10);
|
|
const result = await dataSource.query(
|
|
`INSERT INTO users (id, phone, name, "passwordHash", role, "isActive")
|
|
VALUES (uuid_generate_v4(), '5512345678', 'Test User', $1, 'USER', true)
|
|
RETURNING id`,
|
|
[passwordHash],
|
|
);
|
|
userId = result[0].id;
|
|
|
|
// Create credit balance
|
|
await dataSource.query(
|
|
`INSERT INTO credit_balances (id, "userId", balance, "totalPurchased", "totalConsumed", "totalFromReferrals")
|
|
VALUES (uuid_generate_v4(), $1, 150, 100, 0, 50)`,
|
|
[userId],
|
|
);
|
|
|
|
// Create credit packages
|
|
await dataSource.query(`
|
|
INSERT INTO credit_packages (id, name, description, credits, "priceMXN", "isPopular", "isActive", "sortOrder")
|
|
VALUES
|
|
(uuid_generate_v4(), 'Starter', 'Perfecto para probar', 10, 49.00, false, true, 1),
|
|
(uuid_generate_v4(), 'Basico', 'Para uso regular', 30, 129.00, false, true, 2),
|
|
(uuid_generate_v4(), 'Popular', 'El mas vendido', 75, 299.00, true, true, 3)
|
|
`);
|
|
|
|
// Create some transactions
|
|
await dataSource.query(
|
|
`INSERT INTO credit_transactions (id, "userId", type, amount, "balanceAfter", description)
|
|
VALUES
|
|
(uuid_generate_v4(), $1, 'PURCHASE', 100, 100, 'Compra de paquete Basico'),
|
|
(uuid_generate_v4(), $1, 'REFERRAL_BONUS', 50, 150, 'Bonus por referido'),
|
|
(uuid_generate_v4(), $1, 'CONSUMPTION', -10, 140, 'Procesamiento de video')`,
|
|
[userId],
|
|
);
|
|
|
|
// Generate token
|
|
accessToken = jwtService.sign({ sub: userId });
|
|
});
|
|
|
|
describe('GET /credits/balance', () => {
|
|
it('should return credit balance', async () => {
|
|
const response = await request(app.getHttpServer())
|
|
.get('/credits/balance')
|
|
.set('Authorization', `Bearer ${accessToken}`)
|
|
.expect(200);
|
|
|
|
expect(response.body).toMatchObject({
|
|
balance: 150,
|
|
totalPurchased: 100,
|
|
totalConsumed: 0,
|
|
totalFromReferrals: 50,
|
|
});
|
|
});
|
|
|
|
it('should fail without authentication', async () => {
|
|
await request(app.getHttpServer())
|
|
.get('/credits/balance')
|
|
.expect(401);
|
|
});
|
|
});
|
|
|
|
describe('GET /credits/transactions', () => {
|
|
it('should return transaction history', async () => {
|
|
const response = await request(app.getHttpServer())
|
|
.get('/credits/transactions')
|
|
.set('Authorization', `Bearer ${accessToken}`)
|
|
.expect(200);
|
|
|
|
expect(response.body.transactions).toHaveLength(3);
|
|
expect(response.body.total).toBe(3);
|
|
expect(response.body.page).toBe(1);
|
|
expect(response.body).toHaveProperty('hasMore');
|
|
});
|
|
|
|
it('should support pagination', async () => {
|
|
const response = await request(app.getHttpServer())
|
|
.get('/credits/transactions?page=1&limit=2')
|
|
.set('Authorization', `Bearer ${accessToken}`)
|
|
.expect(200);
|
|
|
|
expect(response.body.transactions).toHaveLength(2);
|
|
expect(response.body.limit).toBe(2);
|
|
expect(response.body.hasMore).toBe(true);
|
|
});
|
|
|
|
it('should fail without authentication', async () => {
|
|
await request(app.getHttpServer())
|
|
.get('/credits/transactions')
|
|
.expect(401);
|
|
});
|
|
});
|
|
|
|
describe('GET /credits/packages', () => {
|
|
it('should return available packages', async () => {
|
|
const response = await request(app.getHttpServer())
|
|
.get('/credits/packages')
|
|
.set('Authorization', `Bearer ${accessToken}`)
|
|
.expect(200);
|
|
|
|
expect(response.body).toHaveLength(3);
|
|
expect(response.body[0]).toHaveProperty('name');
|
|
expect(response.body[0]).toHaveProperty('credits');
|
|
expect(response.body[0]).toHaveProperty('priceMXN');
|
|
|
|
// Check popular flag
|
|
const popularPackage = response.body.find((p: any) => p.isPopular);
|
|
expect(popularPackage.name).toBe('Popular');
|
|
});
|
|
|
|
it('should fail without authentication', async () => {
|
|
await request(app.getHttpServer())
|
|
.get('/credits/packages')
|
|
.expect(401);
|
|
});
|
|
});
|
|
});
|