updated events

This commit is contained in:
Berkay 2025-08-02 20:08:43 +03:00
parent b54bbe2db2
commit 1b87dee60d
9 changed files with 202 additions and 56 deletions

View File

@ -1932,6 +1932,20 @@ model build_ibans {
@@index([updated_at], map: "ix_build_ibans_updated_at") @@index([updated_at], map: "ix_build_ibans_updated_at")
} }
model user_types {
id Int @id @default(autoincrement())
uu_id String @unique(map: "ix_user_types_uu_id") @default(dbgenerated("gen_random_uuid()")) @db.Uuid
type String @db.VarChar
description String @default("") @db.VarChar
type_token String @default("") @db.VarChar
token String @default("") @db.VarChar
occupant_types occupant_types[]
staff staff[]
@@index([type], map: "ix_user_types_type")
@@index([token], map: "ix_user_types_token")
}
/// This model or at least one of its fields has comments in the database, and requires an additional setup for migrations: Read more: https://pris.ly/d/database-comments /// This model or at least one of its fields has comments in the database, and requires an additional setup for migrations: Read more: https://pris.ly/d/database-comments
model build_living_space { model build_living_space {
fix_value Decimal @default(0) @db.Decimal(20, 6) fix_value Decimal @default(0) @db.Decimal(20, 6)
@ -3081,6 +3095,8 @@ model occupant_types {
occupant_category String @default("") @db.VarChar occupant_category String @default("") @db.VarChar
occupant_category_type String @default("") @db.VarChar occupant_category_type String @default("") @db.VarChar
function_retriever String @default("") @db.VarChar function_retriever String @default("") @db.VarChar
user_type_id Int?
user_type_uu_id String? @db.VarChar
occupant_is_unique Boolean @default(false) occupant_is_unique Boolean @default(false)
ref_id String? @db.VarChar(100) ref_id String? @db.VarChar(100)
replication_id Int @default(0) @db.SmallInt replication_id Int @default(0) @db.SmallInt
@ -3103,6 +3119,7 @@ model occupant_types {
build_decision_book_person_occupants build_decision_book_person_occupants[] build_decision_book_person_occupants build_decision_book_person_occupants[]
build_living_space build_living_space[] build_living_space build_living_space[]
build_management build_management[] build_management build_management[]
user_types user_types? @relation(fields: [user_type_id], references: [id], onDelete: NoAction, onUpdate: NoAction)
@@index([created_at], map: "ix_occupant_types_created_at") @@index([created_at], map: "ix_occupant_types_created_at")
@@index([cryp_uu_id], map: "ix_occupant_types_cryp_uu_id") @@index([cryp_uu_id], map: "ix_occupant_types_cryp_uu_id")
@ -3475,7 +3492,9 @@ model staff {
staff_code String @db.VarChar staff_code String @db.VarChar
duties_id Int duties_id Int
duties_uu_id String @db.VarChar duties_uu_id String @db.VarChar
function_retriever String @default("") @db.VarChar // function_retriever String @default("") @db.VarChar
user_type_id Int?
user_type_uu_id String? @db.VarChar
ref_id String? @db.VarChar(100) ref_id String? @db.VarChar(100)
replication_id Int @default(0) @db.SmallInt replication_id Int @default(0) @db.SmallInt
cryp_uu_id String? @db.VarChar cryp_uu_id String? @db.VarChar
@ -3497,6 +3516,7 @@ model staff {
employee_history employee_history[] employee_history employee_history[]
employees employees[] employees employees[]
duties duties @relation(fields: [duties_id], references: [id], onDelete: NoAction, onUpdate: NoAction) duties duties @relation(fields: [duties_id], references: [id], onDelete: NoAction, onUpdate: NoAction)
user_type user_types? @relation(fields: [user_type_id], references: [id], onDelete: NoAction, onUpdate: NoAction)
@@index([created_at], map: "ix_staff_created_at") @@index([created_at], map: "ix_staff_created_at")
@@index([cryp_uu_id], map: "ix_staff_cryp_uu_id") @@index([cryp_uu_id], map: "ix_staff_cryp_uu_id")

View File

@ -8,35 +8,44 @@ import {
Body, Body,
HttpCode, HttpCode,
UseGuards, UseGuards,
ForbiddenException,
Req,
Query,
} from '@nestjs/common'; } from '@nestjs/common';
import { AccountsService } from './accounts.service'; import { AccountsService } from './accounts.service';
import { AuthControlGuard, EndpointControlGuard } from '../middleware/access-control.guard'; import { AuthControlGuard, EndpointControlGuard } from '../middleware/access-control.guard';
@Controller('accounts') @Controller('accounts')
export class AccountsController { export class AccountsController {
constructor(private accountsService: AccountsService) {} constructor(private accountsService: AccountsService) { }
@Get('events')
@HttpCode(200)
@UseGuards(AuthControlGuard, EndpointControlGuard)
async getEvents(@Query() query: any) {
const { url, func } = query;
const events = await this.accountsService.infoEvents(url, func);
return {
events,
message: "Events fetched successfully",
}
}
@Post('filter') @Post('filter')
@HttpCode(200) @HttpCode(200)
@UseGuards(AuthControlGuard, EndpointControlGuard) @UseGuards(AuthControlGuard, EndpointControlGuard)
async filterAccounts(@Body() query: any) { async filterAccounts(@Body() query: any, @Req() req: any) {
const result = await this.accountsService.findWithPagination(query); const driveToken = req.driveToken
const { pagination, data } = result; const redirectToService = await this.accountsService.getEvents();
console.log('redirectToService', redirectToService);
if (data.length === 0) { try {
return { pagination, data: [] }; const functionToCall = redirectToService[driveToken];
return await functionToCall(query);
} catch (error) {
console.error('Error redirecting to service:', error);
throw new ForbiddenException(`This user is not allowed to access this endpoint. Please contact your system administrator.`);
} }
const resultRefined = data.map((rec: any) => ({
...rec,
build_decision_book_payments: rec.build_decision_book_payments?.map(
(pmt: any) => ({
...pmt,
ratePercent:
((pmt.payment_amount / rec.currency_value) * 100).toFixed(2) + '%',
}),
),
}));
return { pagination, data: resultRefined };
} }
} }

View File

@ -8,6 +8,7 @@ import {
AuthControlGuard, AuthControlGuard,
EndpointControlGuard, EndpointControlGuard,
} from '@/src/middleware/access-control.guard'; } from '@/src/middleware/access-control.guard';
import { SuperUsersService } from './superusers/superusers.service';
@Module({ @Module({
imports: [PrismaModule, UtilsModule], imports: [PrismaModule, UtilsModule],
@ -16,7 +17,17 @@ import {
CacheService, CacheService,
AuthControlGuard, AuthControlGuard,
EndpointControlGuard, EndpointControlGuard,
SuperUsersService,
], ],
controllers: [AccountsController], controllers: [AccountsController],
}) })
export class AccountsModule {} export class AccountsModule {
constructor(
private accountsService: AccountsService,
) { }
async onModuleInit() {
const accountEvents = await this.accountsService.infoEvents();
console.dir(accountEvents, { depth: null });
}
}

View File

@ -1,42 +1,80 @@
import { Injectable } from '@nestjs/common'; import { Injectable } from '@nestjs/common';
import { PrismaService } from '@/src/prisma.service'; import { PaginationInfo } from '../utils/pagination-helper';
import { Prisma, account_records } from '@prisma/client'; import { SuperUsersService } from './superusers/superusers.service';
import { CacheService } from '../cache.service'; import crypto from 'crypto';
import { PaginationHelper, PaginationInfo } from '../utils/pagination-helper';
@Injectable() @Injectable()
export class AccountsService { export class AccountsService {
constructor( constructor(
private prisma: PrismaService, private superUsersService: SuperUsersService,
private cacheService: CacheService, ) { }
private paginationHelper: PaginationHelper, events = {
) {} "/accounts/filter:GQKQshahQhGm8HYy4O4Tgx": [
{
"key": "s8OnSnHoQfyfuDk7A1XRww",
"description": "Super Users Filter",
"isDefault": true,
"query": { "query": true, "page": false, "pageSize": false },
"token": "GQKQshahQhGm8HYy4O4Tgx",
"pages": ["accounts"]
// "type": "EMP",
// "fr": "SuperUserEmployee",
}
],
"/accounts/read:GQKQshahQhGm8HYy4O4Tgx": [
{
"key": "s8OnSnHoQfyfuDk7A1XRww",
"description": "Super Users Read",
"isDefault": true,
"query": { "query": true, "page": false, "pageSize": false },
"token": "GQKQshahQhGm8HYy4O4Tgx",
"pages": ["accounts"]
// "type": "EMP",
// "fr": "SuperUserEmployee",
}
]
};
async findAll(filter: any): Promise<Partial<account_records>[]> { createSecureKeyWithoutLib(url: string) {
return this.prisma.account_records.findMany({ const subString = crypto.createHash('sha256').update(url).digest().toString('base64').substring(0, 16)
where: { ...filter }, return subString.replace(/=/g, 'E').replace(/-/g, 'M').replace(/_/g, 'N').replace(/\+/g, 'P').replace(/\//g, 'Q')
});
} }
async findDynamic( async infoEvents(urlRetriever: string | null = null, functionRetriever: string | null = null) {
query: Prisma.account_recordsFindManyArgs, const events = this.events;
): Promise<{ totalCount: number; result: Partial<account_records>[] }> { if (urlRetriever && !functionRetriever) {
const totalCount = await this.prisma.account_records.count({ if (events[urlRetriever]) {
where: query.where, return [[urlRetriever, events[urlRetriever]]];
}); }
const result = await this.prisma.account_records.findMany(query); return [];
return { totalCount, result }; } else if (urlRetriever && functionRetriever) {
if (events[urlRetriever] && events[urlRetriever][functionRetriever]) {
return [[urlRetriever, { [functionRetriever]: events[urlRetriever][functionRetriever] }]];
}
return [];
} else if (!urlRetriever && functionRetriever) {
const filteredEvents: [string, any][] = [];
Object.entries(events).forEach(([url, urlEvents]) => {
if (urlEvents[functionRetriever]) {
filteredEvents.push([url, { [functionRetriever]: urlEvents[functionRetriever] }]);
}
});
return filteredEvents;
} else {
return Object.entries(events);
}
} }
async findWithPagination( async getEvents() {
query: any & { page?: number; pageSize?: number }, return {
): Promise<{ data: any[]; pagination: PaginationInfo }> { "/accounts/filter:GQKQshahQhGm8HYy4O4Tgx:s8OnSnHoQfyfuDk7A1XRww": (query: any) => this.supersUserFilter(query),
return this.paginationHelper.paginate(this.prisma.account_records, query); "/accounts/read:a5b6d9c716f409a7004a:tcc116f409a7004a": (query: any) => this.supersUserFilter(query)
};
} }
async findOne(uuid: string): Promise<Partial<account_records> | null> {
return this.prisma.account_records.findUnique({ async supersUserFilter(query: any & { page?: number; pageSize?: number }): Promise<{ pagination: PaginationInfo; data: any[] }> {
where: { uu_id: uuid }, return this.superUsersService.filter(query);
});
} }
} }

View File

@ -0,0 +1,18 @@
import { Test, TestingModule } from '@nestjs/testing';
import { SuperusersService } from './superusers.service';
describe('SuperusersService', () => {
let service: SuperusersService;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [SuperusersService],
}).compile();
service = module.get<SuperusersService>(SuperusersService);
});
it('should be defined', () => {
expect(service).toBeDefined();
});
});

View File

@ -0,0 +1,30 @@
import { PaginationHelper } from '@/src/utils/pagination-helper';
import { Injectable } from '@nestjs/common';
import { PaginationInfo } from '@/src/utils/pagination-helper';
import { PrismaService } from '@/src/prisma.service';
@Injectable()
export class SuperUsersService {
constructor(
private paginationHelper: PaginationHelper,
private prisma: PrismaService,
) { }
async filter(query: any & { page?: number; pageSize?: number }): Promise<{ pagination: PaginationInfo; data: any[] }> {
console.log("supersServiceFilter query", query)
const result = await this.paginationHelper.findWithPagination(query, this.prisma.account_records);
const { pagination, data } = result;
if (data.length === 0) { return { pagination, data: [] } }
const resultRefined = data.map((rec: any) => ({
...rec,
build_decision_book_payments: rec.build_decision_book_payments?.map(
(pmt: any) => ({
...pmt,
ratePercent: ((pmt.payment_amount / rec.currency_value) * 100).toFixed(2) + '%',
}),
),
}));
return { pagination, data: resultRefined };
}
}

View File

@ -8,7 +8,7 @@ import { RedisHandlers } from '@/src/utils/auth/redis_handlers';
@Injectable() @Injectable()
export class AuthControlGuard implements CanActivate { export class AuthControlGuard implements CanActivate {
constructor(private cacheService: RedisHandlers) {} constructor(private cacheService: RedisHandlers) { }
async canActivate(context: ExecutionContext): Promise<boolean> { async canActivate(context: ExecutionContext): Promise<boolean> {
const req = context.switchToHttp().getRequest(); const req = context.switchToHttp().getRequest();
@ -20,15 +20,18 @@ export class AuthControlGuard implements CanActivate {
@Injectable() @Injectable()
export class EndpointControlGuard implements CanActivate { export class EndpointControlGuard implements CanActivate {
constructor(private cacheService: RedisHandlers) {} constructor(private cacheService: RedisHandlers) { }
async canActivate(context: ExecutionContext): Promise<boolean> { async canActivate(context: ExecutionContext): Promise<boolean> {
const req = context.switchToHttp().getRequest(); const req = context.switchToHttp().getRequest();
// const selectToken = this.cacheService.mergeSelectKey(req); // const selectToken = this.cacheService.mergeSelectKey(req);
// const method = req.method; const method = req.method;
// const path = req.route?.path; const path = req.route?.path;
const accessObject = await this.cacheService.getSelectFromRedis(req); console.log('EndpointControlGuard', method, 'path', path);
console.log('EndpointControlGuard', accessObject); // const accessObject = await this.cacheService.getSelectFromRedis(req);
// console.log('EndpointControlGuard', accessObject);
req.driveToken = "c5b6d9c7-9115-4825-bcc1-16f409a7004a"
// console.log('EndpointControlGuard', req.driveToken);
return true; return true;
} }
} }

View File

@ -18,7 +18,7 @@ type ModelDelegate = {
@Injectable() @Injectable()
export class PaginationHelper { export class PaginationHelper {
constructor(private prisma: PrismaService) {} constructor(private prisma: PrismaService) { }
/** /**
* Sayfalama destekli sorgu yapar * Sayfalama destekli sorgu yapar
@ -55,4 +55,12 @@ export class PaginationHelper {
}, },
}; };
} }
async findWithPagination(
query: any & { page?: number; pageSize?: number },
service: ModelDelegate,
): Promise<{ data: any[]; pagination: PaginationInfo }> {
console.log("findWithPagination query", query)
return this.paginate(service, query);
}
} }

View File

@ -0,0 +1,9 @@
import { NextRequest, NextResponse } from "next/server";
export async function POST(req: NextRequest) {
const { type } = await req.json();
}
export async function GET(req: NextRequest, { params }: { params: Promise<{ type: string }> }) {
const { type } = await params;
}