Merge pull request 'wip-SPG-548' (#5) from wip-SPG-548 into development

Reviewed-on: #5
pull/6/head
aswin 2024-06-26 06:52:24 +00:00
commit 9f471aafbf
37 changed files with 699 additions and 48 deletions

View File

@ -55,7 +55,7 @@ export class ValidateRelationHelper<Entity> {
if (relation.singleQuery) { if (relation.singleQuery) {
const relationColumn = data[relation.relation]?.[`${ relation.singleQuery[0] }`] const relationColumn = data[relation.relation]?.[`${ relation.singleQuery[0] }`]
if (this.mappingValidator(relationColumn, relation.singleQuery[1], relation.singleQuery[2])) if (!!relationColumn && this.mappingValidator(relationColumn, relation.singleQuery[1], relation.singleQuery[2]))
throw new UnprocessableEntityException(message); throw new UnprocessableEntityException(message);
} else if (data[`total_${ relation.relation } `]) } else if (data[`total_${ relation.relation } `])
throw new UnprocessableEntityException(message); throw new UnprocessableEntityException(message);

View File

@ -6,7 +6,7 @@ import {
} from 'typeorm'; } from 'typeorm';
export abstract class BaseDataService<Entity> { export abstract class BaseDataService<Entity> {
constructor(private repository: Repository<Entity>) {} constructor(private repository: Repository<Entity>) { }
getRepository(): Repository<Entity> { getRepository(): Repository<Entity> {
return this.repository; return this.repository;
@ -58,7 +58,8 @@ export abstract class BaseDataService<Entity> {
entityTarget: EntityTarget<Entity>, entityTarget: EntityTarget<Entity>,
findManyOptions: FindManyOptions<Entity>, findManyOptions: FindManyOptions<Entity>,
): Promise<void> { ): Promise<void> {
await queryRunner.manager.delete(entityTarget, findManyOptions); const datas = await queryRunner.manager.find(entityTarget, findManyOptions)
await queryRunner.manager.delete(entityTarget, datas?.map(item => item['id']));
} }
async getOneByOptions(findOneOptions): Promise<Entity> { async getOneByOptions(findOneOptions): Promise<Entity> {

View File

@ -2,6 +2,8 @@ import { BatchResult } from 'src/core/response/domain/ok-response.interface';
import { BaseManager } from '../base.manager'; import { BaseManager } from '../base.manager';
import { HttpStatus, NotFoundException } from '@nestjs/common'; import { HttpStatus, NotFoundException } from '@nestjs/common';
import { ValidateRelationHelper } from 'src/core/helpers/validation/validate-relation.helper'; import { ValidateRelationHelper } from 'src/core/helpers/validation/validate-relation.helper';
import { RecordLog } from 'src/modules/configuration/log/domain/entities/log.event';
import { OPERATION } from 'src/core/strings/constants/base.constants';
export abstract class BaseBatchDeleteManager<Entity> extends BaseManager { export abstract class BaseBatchDeleteManager<Entity> extends BaseManager {
protected dataIds: string[]; protected dataIds: string[];
@ -36,7 +38,7 @@ export abstract class BaseBatchDeleteManager<Entity> extends BaseManager {
if (!entity) { if (!entity) {
throw new NotFoundException({ throw new NotFoundException({
statusCode: HttpStatus.NOT_FOUND, statusCode: HttpStatus.NOT_FOUND,
message: `Failed! Entity with id ${id} not found`, message: `Failed! Entity with id ${ id } not found`,
error: 'Entity Not Found', error: 'Entity Not Found',
}); });
} }
@ -49,12 +51,13 @@ export abstract class BaseBatchDeleteManager<Entity> extends BaseManager {
this.tableName, this.tableName,
).execute(); ).execute();
await this.dataService.deleteById( const result = await this.dataService.deleteById(
this.queryRunner, this.queryRunner,
this.entityTarget, this.entityTarget,
id, id,
); );
this.publishEvents(entity, result);
totalSuccess = totalSuccess + 1; totalSuccess = totalSuccess + 1;
} catch (error) { } catch (error) {
totalFailed = totalFailed + 1; totalFailed = totalFailed + 1;
@ -72,4 +75,33 @@ export abstract class BaseBatchDeleteManager<Entity> extends BaseManager {
abstract validateData(data: Entity): Promise<void>; abstract validateData(data: Entity): Promise<void>;
abstract getResult(): BatchResult; abstract getResult(): BatchResult;
async publishEvents(dataOld, dataNew) {
this.eventBus.publish(
new RecordLog({
id: dataNew['id'],
old: dataOld,
data: dataNew,
user: this.user,
description: `${ this.user.name } delete batch data ${ this.tableName }`,
module: this.tableName,
op: OPERATION.DELETE,
}),
);
if (!this.eventTopics.length) return;
for (const topic of this.eventTopics) {
this.eventBus.publishAll([
new topic.topic({
id: dataNew['id'],
old: dataOld,
data: dataNew,
user: this.user,
description: '',
module: this.tableName,
op: OPERATION.UPDATE,
}),
]);
}
}
} }

View File

@ -1,8 +1,9 @@
import { BatchResult } from 'src/core/response/domain/ok-response.interface'; import { BatchResult } from 'src/core/response/domain/ok-response.interface';
import { BaseManager } from '../base.manager'; import { BaseManager } from '../base.manager';
import { HttpStatus, NotFoundException } from '@nestjs/common'; import { HttpStatus, NotFoundException } from '@nestjs/common';
import { STATUS } from 'src/core/strings/constants/base.constants'; import { OPERATION, STATUS } from 'src/core/strings/constants/base.constants';
import { ValidateRelationHelper } from 'src/core/helpers/validation/validate-relation.helper'; import { ValidateRelationHelper } from 'src/core/helpers/validation/validate-relation.helper';
import { RecordLog } from 'src/modules/configuration/log/domain/entities/log.event';
export abstract class BaseBatchUpdateStatusManager<Entity> extends BaseManager { export abstract class BaseBatchUpdateStatusManager<Entity> extends BaseManager {
protected dataIds: string[]; protected dataIds: string[];
@ -52,7 +53,7 @@ export abstract class BaseBatchUpdateStatusManager<Entity> extends BaseManager {
this.tableName, this.tableName,
).execute(); ).execute();
await this.dataService.update( const result = await this.dataService.update(
this.queryRunner, this.queryRunner,
this.entityTarget, this.entityTarget,
{ id: id }, { id: id },
@ -63,6 +64,9 @@ export abstract class BaseBatchUpdateStatusManager<Entity> extends BaseManager {
updated_at: new Date().getTime(), updated_at: new Date().getTime(),
}, },
); );
this.publishEvents(entity, result);
totalSuccess = totalSuccess + 1; totalSuccess = totalSuccess + 1;
} catch (error) { } catch (error) {
totalFailed = totalFailed + 1; totalFailed = totalFailed + 1;
@ -80,4 +84,44 @@ export abstract class BaseBatchUpdateStatusManager<Entity> extends BaseManager {
abstract validateData(data: Entity): Promise<void>; abstract validateData(data: Entity): Promise<void>;
abstract getResult(): BatchResult; abstract getResult(): BatchResult;
async publishEvents(dataOld, dataNew) {
this.eventBus.publish(
new RecordLog({
id: dataNew['id'],
old: dataOld,
data: dataNew,
user: this.user,
description: `${ this.user.name } update batch data ${ this.tableName }`,
module: this.tableName,
op: OPERATION.UPDATE,
}),
);
if (!this.eventTopics.length) return;
for (const topic of this.eventTopics) {
let data;
if (!topic.relations) {
data = await this.dataService.getOneByOptions({
where: {
id: dataNew.id,
},
relations: topic.relations,
})
}
this.eventBus.publishAll([
new topic.topic({
id: data?.['id'] ?? dataNew?.['id'],
old: dataOld,
data: data ?? dataNew,
user: this.user,
description: '',
module: this.tableName,
op: OPERATION.UPDATE,
}),
]);
}
}
} }

View File

@ -1,6 +1,8 @@
import { HttpStatus, UnprocessableEntityException } from '@nestjs/common'; import { HttpStatus, UnprocessableEntityException } from '@nestjs/common';
import { BaseManager } from '../base.manager'; import { BaseManager } from '../base.manager';
import { ValidateRelationHelper } from 'src/core/helpers/validation/validate-relation.helper'; import { ValidateRelationHelper } from 'src/core/helpers/validation/validate-relation.helper';
import { RecordLog } from 'src/modules/configuration/log/domain/entities/log.event';
import { OPERATION } from 'src/core/strings/constants/base.constants';
export abstract class BaseDeleteManager<Entity> extends BaseManager { export abstract class BaseDeleteManager<Entity> extends BaseManager {
protected dataId: string; protected dataId: string;
@ -21,7 +23,7 @@ export abstract class BaseDeleteManager<Entity> extends BaseManager {
if (!this.data) if (!this.data)
throw new UnprocessableEntityException({ throw new UnprocessableEntityException({
statusCode: HttpStatus.UNPROCESSABLE_ENTITY, statusCode: HttpStatus.UNPROCESSABLE_ENTITY,
message: `Data with id ${this.dataId} not found`, message: `Data with id ${ this.dataId } not found`,
error: 'Unprocessable Entity', error: 'Unprocessable Entity',
}); });
@ -41,7 +43,38 @@ export abstract class BaseDeleteManager<Entity> extends BaseManager {
this.entityTarget, this.entityTarget,
this.dataId, this.dataId,
); );
this.publishEvents();
} }
abstract getResult(): string; abstract getResult(): string;
async publishEvents() {
this.eventBus.publish(
new RecordLog({
id: this.result['id'],
old: null,
data: this.result,
user: this.user,
description: `${ this.user.name } delete data ${ this.tableName }`,
module: this.tableName,
op: OPERATION.CREATE,
}),
);
if (!this.eventTopics.length) return;
for (const topic of this.eventTopics) {
this.eventBus.publishAll([
new topic.topic({
id: topic.data['id'],
old: null,
data: topic.data,
user: this.user,
description: '',
module: this.tableName,
op: OPERATION.DELETE,
}),
]);
}
}
} }

View File

@ -1,11 +1,13 @@
import { ValidateRelationHelper } from 'src/core/helpers/validation/validate-relation.helper'; import { ValidateRelationHelper } from 'src/core/helpers/validation/validate-relation.helper';
import { BaseManager } from '../base.manager'; import { BaseManager } from '../base.manager';
import { STATUS } from 'src/core/strings/constants/base.constants'; import { OPERATION, STATUS } from 'src/core/strings/constants/base.constants';
import { UserPrivilegeModel } from 'src/modules/user-related/user-privilege/data/models/user-privilege.model'; import * as _ from 'lodash';
import { RecordLog } from 'src/modules/configuration/log/domain/entities/log.event';
export abstract class BaseUpdateStatusManager<Entity> extends BaseManager { export abstract class BaseUpdateStatusManager<Entity> extends BaseManager {
protected dataId: string; protected dataId: string;
protected result: Entity; protected result: Entity;
protected oldData: Entity;
protected dataStatus: STATUS; protected dataStatus: STATUS;
protected duplicateColumn: string[]; protected duplicateColumn: string[];
abstract get entityTarget(): any; abstract get entityTarget(): any;
@ -16,13 +18,17 @@ export abstract class BaseUpdateStatusManager<Entity> extends BaseManager {
} }
async prepareData(): Promise<void> { async prepareData(): Promise<void> {
this.data = new UserPrivilegeModel(); this.data = await this.dataService.getOneByOptions({
where: {
id: this.dataId,
}
})
this.oldData = _.cloneDeep(this.data);
Object.assign(this.data, { Object.assign(this.data, {
editor_id: this.user.id, editor_id: this.user.id,
editor_name: this.user.name, editor_name: this.user.name,
updated_at: new Date().getTime(), updated_at: new Date().getTime(),
id: this.dataId,
status: this.dataStatus, status: this.dataStatus,
}); });
} }
@ -41,7 +47,49 @@ export abstract class BaseUpdateStatusManager<Entity> extends BaseManager {
{ id: this.dataId }, { id: this.dataId },
this.data, this.data,
); );
this.publishEvents();
} }
abstract getResult(): string; abstract getResult(): string;
async publishEvents() {
this.eventBus.publish(
new RecordLog({
id: this.result['id'],
old: this.oldData,
data: this.result,
user: this.user,
description: `${ this.user.name } update status data ${ this.tableName } to ${ this.dataStatus }`,
module: this.tableName,
op: OPERATION.UPDATE,
}),
);
if (!this.eventTopics.length) return;
for (const topic of this.eventTopics) {
let data;
if (!topic.data) {
data = await this.dataService.getOneByOptions({
where: {
id: this.dataId
},
relations: topic.relations,
})
}
this.eventBus.publishAll([
new topic.topic({
id: data?.['id'] ?? topic?.data?.['id'],
old: this.oldData,
data: data ?? topic.data,
user: this.user,
description: '',
module: this.tableName,
op: OPERATION.UPDATE,
}),
]);
}
}
} }

View File

@ -2,10 +2,14 @@ import { CheckDuplicateHelper } from 'src/core/helpers/query/check-duplicate.hel
import { BaseManager } from '../base.manager'; import { BaseManager } from '../base.manager';
import { ValidateRelationHelper } from 'src/core/helpers/validation/validate-relation.helper'; import { ValidateRelationHelper } from 'src/core/helpers/validation/validate-relation.helper';
import { columnUniques } from 'src/core/strings/constants/interface.constants'; import { columnUniques } from 'src/core/strings/constants/interface.constants';
import { RecordLog } from 'src/modules/configuration/log/domain/entities/log.event';
import { OPERATION } from 'src/core/strings/constants/base.constants';
import { HttpStatus, NotFoundException } from '@nestjs/common';
export abstract class BaseUpdateManager<Entity> extends BaseManager { export abstract class BaseUpdateManager<Entity> extends BaseManager {
protected dataId: string; protected dataId: string;
protected result: Entity; protected result: Entity;
protected oldData: Entity;
protected duplicateColumn: string[]; protected duplicateColumn: string[];
abstract get entityTarget(): any; abstract get entityTarget(): any;
abstract get uniqueColumns(): columnUniques[]; abstract get uniqueColumns(): columnUniques[];
@ -34,6 +38,18 @@ export abstract class BaseUpdateManager<Entity> extends BaseManager {
} }
async process(): Promise<void> { async process(): Promise<void> {
this.oldData = await this.dataService.getOneByOptions({
where: { id: this.dataId },
});
if (!this.oldData) {
throw new NotFoundException({
statusCode: HttpStatus.NOT_FOUND,
message: `Failed! Entity with id ${ this.dataId } not found`,
error: 'Entity Not Found',
});
}
await new ValidateRelationHelper( await new ValidateRelationHelper(
this.dataId, this.dataId,
this.dataService, this.dataService,
@ -47,6 +63,8 @@ export abstract class BaseUpdateManager<Entity> extends BaseManager {
{ id: this.dataId }, { id: this.dataId },
this.data, this.data,
); );
this.publishEvents();
} }
async getResult(): Promise<Entity> { async getResult(): Promise<Entity> {
@ -56,4 +74,44 @@ export abstract class BaseUpdateManager<Entity> extends BaseManager {
}, },
}); });
} }
async publishEvents() {
this.eventBus.publish(
new RecordLog({
id: this.result['id'],
old: this.oldData,
data: this.result,
user: this.user,
description: `${ this.user.name } update data ${ this.tableName }`,
module: this.tableName,
op: OPERATION.UPDATE,
}),
);
if (!this.eventTopics.length) return;
for (const topic of this.eventTopics) {
let data;
if (!topic.data) {
data = await this.dataService.getOneByOptions({
where: {
id: this.dataId
},
relations: topic.relations,
})
}
this.eventBus.publishAll([
new topic.topic({
id: data?.['id'] ?? topic?.data?.['id'],
old: this.oldData,
data: data ?? topic.data,
user: this.user,
description: '',
module: this.tableName,
op: OPERATION.UPDATE,
}),
]);
}
}
} }

View File

@ -5,6 +5,7 @@ import { SelectQueryBuilder } from 'typeorm';
export interface EventTopics { export interface EventTopics {
topic: any; topic: any;
data?: any; data?: any;
relations?: string[];
} }
export interface validateRelations { export interface validateRelations {

View File

@ -3,14 +3,25 @@ import { CouchDataController } from './infrastructure/couch.controller';
import { Module } from '@nestjs/common'; import { Module } from '@nestjs/common';
import { CouchService } from './data/services/couch.service'; import { CouchService } from './data/services/couch.service';
import { CqrsModule } from '@nestjs/cqrs'; import { CqrsModule } from '@nestjs/cqrs';
import { PaymentMethodUpdatedHandler, PaymentMethodDeletedHandler } from './domain/managers/payment-method.handler';
import { VipCategoryDeletedHandler, VipCategoryUpdatedHandler } from './domain/managers/vip-category.handler';
import { SeasonPeriodDeletedHandler, SeasonPeriodUpdatedHandler } from './domain/managers/season-period.handler';
@Module({ @Module({
imports: [ imports: [
ConfigModule.forRoot(), ConfigModule.forRoot(),
// TypeOrmModule.forFeature([UserPrivilegeModel], CONNECTION_NAME.DEFAULT),
CqrsModule, CqrsModule,
], ],
controllers: [CouchDataController], controllers: [CouchDataController],
providers: [CouchService], providers: [
PaymentMethodDeletedHandler,
PaymentMethodUpdatedHandler,
VipCategoryDeletedHandler,
VipCategoryUpdatedHandler,
SeasonPeriodDeletedHandler,
SeasonPeriodUpdatedHandler,
CouchService,
],
}) })
export class CouchModule {} export class CouchModule { }

View File

@ -5,7 +5,7 @@ import { ChangeDocEvent } from '../../domain/events/change-doc.event';
@Injectable() @Injectable()
export class CouchService { export class CouchService {
constructor(private eventBus: EventBus) {} constructor(private eventBus: EventBus) { }
async onModuleInit() { async onModuleInit() {
const nano = require('nano')('http://root:password@172.10.10.2:5970'); const nano = require('nano')('http://root:password@172.10.10.2:5970');
@ -15,7 +15,7 @@ export class CouchService {
this.changeDoc(change, database); this.changeDoc(change, database);
}); });
console.log(`start listen database ${database}`); console.log(`start listen database ${ database }`);
} }
} }
@ -28,4 +28,28 @@ export class CouchService {
}), }),
); );
} }
public async createDoc(data, database) {
const nano = require('nano')('http://root:password@172.10.10.2:5970');
const db = nano.use(database);
return await db.insert(data);
}
public async deleteDoc(data, database) {
const nano = require('nano')('http://root:password@172.10.10.2:5970');
const db = nano.use(database);
const result = await db.get(data.id)
await db.destroy(data.id, result._rev);
}
public async updateDoc(data, database) {
const nano = require('nano')('http://root:password@172.10.10.2:5970');
const db = nano.use(database);
const result = await db.get(data.id)
console.log(result, 'dsa')
await db.insert({
...data,
_rev: result._rev
});
}
} }

View File

@ -0,0 +1,81 @@
import { EventsHandler, IEventHandler } from "@nestjs/cqrs";
import { CouchService } from "../../data/services/couch.service";
import { STATUS } from "src/core/strings/constants/base.constants";
import { ItemDeletedEvent } from "src/modules/item-related/item/domain/entities/event/item-deleted.event";
import { ItemUpdatedEvent } from "src/modules/item-related/item/domain/entities/event/item-updated.event";
import { ItemChangeStatusEvent } from "src/modules/item-related/item/domain/entities/event/item-change-status.event";
import { ItemDataService } from "src/modules/item-related/item/data/services/item-data.service";
@EventsHandler(ItemDeletedEvent)
export class ItemDeletedHandler implements IEventHandler<ItemDeletedEvent> {
constructor(
private couchService: CouchService
) { }
async handle(event: ItemDeletedEvent) {
const data = await this.couchService.deleteDoc({
_id: event.data.id,
...event.data.data
}, 'item');
}
}
@EventsHandler(ItemChangeStatusEvent, ItemUpdatedEvent)
export class ItemUpdatedHandler implements IEventHandler<ItemChangeStatusEvent> {
constructor(
private couchService: CouchService,
private itemService: ItemDataService,
) { }
async handle(event: ItemChangeStatusEvent) {
const dataOld = event.data.old;
const data = event.data.data;
const dataItem = await this.itemService.getOneByOptions({
where: {
id: data.id
},
relations: [
'item_category',
'bundling_items',
'bundling_items.item_category',
'item_rates',
'item_rates.item',
'item_rates.season_period',
'item_rates.season_period.season_type',
]
})
// change status to active
if (dataOld?.status != data.status && data.status == STATUS.ACTIVE) {
await this.couchService.createDoc(
{
_id: data.id,
...dataItem
},
'item'
);
}
else if (dataOld?.status != data.status) {
await this.couchService.deleteDoc(
{
_id: data.id,
...dataItem
},
'item'
);
}
// update
else {
await this.couchService.updateDoc(
{
_id: data.id,
...dataItem
},
'item'
);
}
}
}

View File

@ -0,0 +1,65 @@
import { EventsHandler, IEventHandler } from "@nestjs/cqrs";
import { CouchService } from "../../data/services/couch.service";
import { STATUS } from "src/core/strings/constants/base.constants";
import { PaymentMethodDeletedEvent } from "src/modules/transaction/payment-method/domain/entities/event/payment-method-deleted.event";
import { PaymentMethodUpdatedEvent } from "src/modules/transaction/payment-method/domain/entities/event/payment-method-updated.event";
import { PaymentMethodChangeStatusEvent } from "src/modules/transaction/payment-method/domain/entities/event/payment-method-change-status.event";
@EventsHandler(PaymentMethodDeletedEvent)
export class PaymentMethodDeletedHandler implements IEventHandler<PaymentMethodDeletedEvent> {
constructor(
private couchService: CouchService
) { }
async handle(event: PaymentMethodDeletedEvent) {
const data = await this.couchService.deleteDoc({
_id: event.data.id,
...event.data.data
}, 'payment_method');
}
}
@EventsHandler(PaymentMethodChangeStatusEvent, PaymentMethodUpdatedEvent)
export class PaymentMethodUpdatedHandler implements IEventHandler<PaymentMethodChangeStatusEvent> {
constructor(
private couchService: CouchService
) { }
async handle(event: PaymentMethodChangeStatusEvent) {
const dataOld = event.data.old;
const data = event.data.data;
// change status to active
if (dataOld?.status != data.status && data.status == STATUS.ACTIVE) {
await this.couchService.createDoc(
{
_id: data.id,
...data
},
'payment_method'
);
}
else if (dataOld?.status != data.status) {
await this.couchService.deleteDoc(
{
_id: data.id,
...data
},
'payment_method'
);
}
// update
else {
await this.couchService.updateDoc(
{
_id: data.id,
...data
},
'payment_method'
);
}
}
}

View File

@ -0,0 +1,65 @@
import { EventsHandler, IEventHandler } from "@nestjs/cqrs";
import { CouchService } from "../../data/services/couch.service";
import { STATUS } from "src/core/strings/constants/base.constants";
import { SeasonPeriodDeletedEvent } from "src/modules/season-related/season-period/domain/entities/event/season-period-deleted.event";
import { SeasonPeriodChangeStatusEvent } from "src/modules/season-related/season-period/domain/entities/event/season-period-change-status.event";
import { SeasonPeriodUpdatedEvent } from "src/modules/season-related/season-period/domain/entities/event/season-period-updated.event";
@EventsHandler(SeasonPeriodDeletedEvent)
export class SeasonPeriodDeletedHandler implements IEventHandler<SeasonPeriodDeletedEvent> {
constructor(
private couchService: CouchService
) { }
async handle(event: SeasonPeriodDeletedEvent) {
const data = await this.couchService.deleteDoc({
_id: event.data.id,
...event.data.data
}, 'season_period');
}
}
@EventsHandler(SeasonPeriodChangeStatusEvent, SeasonPeriodUpdatedEvent)
export class SeasonPeriodUpdatedHandler implements IEventHandler<SeasonPeriodChangeStatusEvent> {
constructor(
private couchService: CouchService
) { }
async handle(event: SeasonPeriodChangeStatusEvent) {
const dataOld = event.data.old;
const data = event.data.data;
// change status to active
if (dataOld?.status != data.status && data.status == STATUS.ACTIVE) {
await this.couchService.createDoc(
{
_id: data.id,
...data
},
'season_period'
);
}
else if (dataOld?.status != data.status) {
await this.couchService.deleteDoc(
{
_id: data.id,
...data
},
'season_period'
);
}
// update
else {
await this.couchService.updateDoc(
{
_id: data.id,
...data
},
'season_period'
);
}
}
}

View File

@ -0,0 +1,82 @@
import { EventsHandler, IEventHandler } from "@nestjs/cqrs";
import { CouchService } from "../../data/services/couch.service";
import { STATUS } from "src/core/strings/constants/base.constants";
import { UserDeletedEvent } from "src/modules/user-related/user/domain/entities/event/user-deleted.event";
import { UserChangeStatusEvent } from "src/modules/user-related/user/domain/entities/event/user-change-status.event";
import { UserUpdatedEvent } from "src/modules/user-related/user/domain/entities/event/user-updated.event";
import { UserDataService } from "src/modules/user-related/user/data/services/user-data.service";
@EventsHandler(UserDeletedEvent)
export class UserDeletedHandler implements IEventHandler<UserDeletedEvent> {
constructor(
private couchService: CouchService
) { }
async handle(event: UserDeletedEvent) {
const data = await this.couchService.deleteDoc({
_id: event.data.id,
...event.data.data
}, 'user');
}
}
@EventsHandler(UserChangeStatusEvent, UserUpdatedEvent)
export class UserUpdatedHandler implements IEventHandler<UserChangeStatusEvent> {
constructor(
private couchService: CouchService,
private userService: UserDataService,
) { }
async handle(event: UserChangeStatusEvent) {
const dataOld = event.data.old;
const data = event.data.data;
const user = await this.userService.getOneByOptions({
where: {
id: data.id
},
relations: [
'user_privilege',
'user_privilege.user_privilege_configurations'
]
}).then(item => {
const user_privilege_configurations = item['user_privilege']?.user_privilege_configurations?.filter(config => config.module == "POS")
Object.assign(item['user_privilege'], {
user_privilege_configurations: user_privilege_configurations
})
return item
})
// change status to active
if (dataOld?.status != data.status && data.status == STATUS.ACTIVE) {
await this.couchService.createDoc(
{
_id: data.id,
...user
},
'user'
);
}
else if (dataOld?.status != data.status) {
await this.couchService.deleteDoc(
{
_id: data.id,
...user
},
'user'
);
}
// update
else {
await this.couchService.updateDoc(
{
_id: data.id,
...user
},
'user'
);
}
}
}

View File

@ -0,0 +1,65 @@
import { EventsHandler, IEventHandler } from "@nestjs/cqrs";
import { CouchService } from "../../data/services/couch.service";
import { VipCategoryDeletedEvent } from "src/modules/transaction/vip-category/domain/entities/event/vip-category-deleted.event";
import { VipCategoryChangeStatusEvent } from "src/modules/transaction/vip-category/domain/entities/event/vip-category-change-status.event";
import { VipCategoryUpdatedEvent } from "src/modules/transaction/vip-category/domain/entities/event/vip-category-updated.event";
import { STATUS } from "src/core/strings/constants/base.constants";
@EventsHandler(VipCategoryDeletedEvent)
export class VipCategoryDeletedHandler implements IEventHandler<VipCategoryDeletedEvent> {
constructor(
private couchService: CouchService
) { }
async handle(event: VipCategoryDeletedEvent) {
const data = await this.couchService.deleteDoc({
_id: event.data.id,
...event.data.data
}, 'vip_category');
}
}
@EventsHandler(VipCategoryChangeStatusEvent, VipCategoryUpdatedEvent)
export class VipCategoryUpdatedHandler implements IEventHandler<VipCategoryChangeStatusEvent> {
constructor(
private couchService: CouchService
) { }
async handle(event: VipCategoryChangeStatusEvent) {
const dataOld = event.data.old;
const data = event.data.data;
// change status to active
if (dataOld?.status != data.status && data.status == STATUS.ACTIVE) {
await this.couchService.createDoc(
{
_id: data.id,
...data
},
'vip_category'
);
}
else if (dataOld?.status != data.status) {
await this.couchService.deleteDoc(
{
_id: data.id,
...data
},
'vip_category'
);
}
// update
else {
await this.couchService.updateDoc(
{
_id: data.id,
...data
},
'vip_category'
);
}
}
}

View File

@ -90,12 +90,36 @@ export class IndexItemRateManager extends BaseIndexManager<ItemEntity> {
} }
get specificFilter(): Param[] { get specificFilter(): Param[] {
return []; return [
{
cols: `${ this.tableName }.name`,
data: this.filterParam.names,
},
{
cols: `${ this.tableName }.item_type::text`,
data: this.filterParam.item_types,
},
{
cols: `${ this.tableName }.limit_type::text`,
data: this.filterParam.limit_types,
},
{
cols: `item_category.name`,
data: this.filterParam.item_categories,
},
];
} }
setQueryFilter( setQueryFilter(
queryBuilder: SelectQueryBuilder<ItemEntity>, queryBuilder: SelectQueryBuilder<ItemEntity>,
): SelectQueryBuilder<ItemEntity> { ): SelectQueryBuilder<ItemEntity> {
if (this.filterParam.tenant_ids?.length) {
queryBuilder.andWhere(`${ this.tableName }.tenant_id In (:...tenantIds)`, {
tenantIds: this.filterParam.tenant_ids,
});
} else if (!this.filterParam.all_item) {
queryBuilder.andWhere(`${ this.tableName }.tenant_id Is Null`);
}
return queryBuilder; return queryBuilder;
} }

View File

@ -1,4 +1,4 @@
import { HttpStatus, Injectable, UnprocessableEntityException } from '@nestjs/common'; import { Injectable } from '@nestjs/common';
import { BaseUpdateStatusManager } from 'src/core/modules/domain/usecase/managers/base-update-status.manager'; import { BaseUpdateStatusManager } from 'src/core/modules/domain/usecase/managers/base-update-status.manager';
import { ItemEntity } from '../../entities/item.entity'; import { ItemEntity } from '../../entities/item.entity';
import { import {

View File

@ -11,7 +11,7 @@ import { SeasonPeriodChangeStatusEvent } from '../../entities/event/season-perio
@Injectable() @Injectable()
export class ActiveSeasonPeriodManager extends BaseUpdateStatusManager<SeasonPeriodEntity> { export class ActiveSeasonPeriodManager extends BaseUpdateStatusManager<SeasonPeriodEntity> {
getResult(): string { getResult(): string {
return `Success active data ${this.result.id}`; return `Success active data ${ this.result.id }`;
} }
async validateProcess(): Promise<void> { async validateProcess(): Promise<void> {
@ -38,7 +38,9 @@ export class ActiveSeasonPeriodManager extends BaseUpdateStatusManager<SeasonPer
return [ return [
{ {
topic: SeasonPeriodChangeStatusEvent, topic: SeasonPeriodChangeStatusEvent,
data: this.data, relations: [
'season_type'
]
}, },
]; ];
} }

View File

@ -35,6 +35,9 @@ export class BatchActiveSeasonPeriodManager extends BaseBatchUpdateStatusManager
return [ return [
{ {
topic: SeasonPeriodChangeStatusEvent, topic: SeasonPeriodChangeStatusEvent,
relations: [
'season_type'
]
}, },
]; ];
} }

View File

@ -35,6 +35,9 @@ export class BatchConfirmSeasonPeriodManager extends BaseBatchUpdateStatusManage
return [ return [
{ {
topic: SeasonPeriodChangeStatusEvent, topic: SeasonPeriodChangeStatusEvent,
relations: [
'season_type'
]
}, },
]; ];
} }

View File

@ -35,6 +35,9 @@ export class BatchInactiveSeasonPeriodManager extends BaseBatchUpdateStatusManag
return [ return [
{ {
topic: SeasonPeriodChangeStatusEvent, topic: SeasonPeriodChangeStatusEvent,
relations: [
'season_type'
]
}, },
]; ];
} }

View File

@ -11,7 +11,7 @@ import { SeasonPeriodChangeStatusEvent } from '../../entities/event/season-perio
@Injectable() @Injectable()
export class ConfirmSeasonPeriodManager extends BaseUpdateStatusManager<SeasonPeriodEntity> { export class ConfirmSeasonPeriodManager extends BaseUpdateStatusManager<SeasonPeriodEntity> {
getResult(): string { getResult(): string {
return `Success active data ${this.result.id}`; return `Success active data ${ this.result.id }`;
} }
async validateProcess(): Promise<void> { async validateProcess(): Promise<void> {
@ -38,7 +38,9 @@ export class ConfirmSeasonPeriodManager extends BaseUpdateStatusManager<SeasonPe
return [ return [
{ {
topic: SeasonPeriodChangeStatusEvent, topic: SeasonPeriodChangeStatusEvent,
data: this.data, relations: [
'season_type'
]
}, },
]; ];
} }

View File

@ -11,7 +11,7 @@ import { SeasonPeriodChangeStatusEvent } from '../../entities/event/season-perio
@Injectable() @Injectable()
export class InactiveSeasonPeriodManager extends BaseUpdateStatusManager<SeasonPeriodEntity> { export class InactiveSeasonPeriodManager extends BaseUpdateStatusManager<SeasonPeriodEntity> {
getResult(): string { getResult(): string {
return `Success inactive data ${this.result.id}`; return `Success inactive data ${ this.result.id }`;
} }
async validateProcess(): Promise<void> { async validateProcess(): Promise<void> {
@ -38,7 +38,9 @@ export class InactiveSeasonPeriodManager extends BaseUpdateStatusManager<SeasonP
return [ return [
{ {
topic: SeasonPeriodChangeStatusEvent, topic: SeasonPeriodChangeStatusEvent,
data: this.data, relations: [
'season_type'
]
}, },
]; ];
} }

View File

@ -45,7 +45,9 @@ export class UpdateSeasonPeriodManager extends BaseUpdateManager<SeasonPeriodEnt
return [ return [
{ {
topic: SeasonPeriodUpdatedEvent, topic: SeasonPeriodUpdatedEvent,
data: this.data, relations: [
'season_type'
]
}, },
]; ];
} }

View File

@ -11,7 +11,7 @@ import { PaymentMethodChangeStatusEvent } from '../../entities/event/payment-met
@Injectable() @Injectable()
export class ActivePaymentMethodManager extends BaseUpdateStatusManager<PaymentMethodEntity> { export class ActivePaymentMethodManager extends BaseUpdateStatusManager<PaymentMethodEntity> {
getResult(): string { getResult(): string {
return `Success active data ${this.result.account_name}`; return `Success active data ${ this.result.account_name }`;
} }
async validateProcess(): Promise<void> { async validateProcess(): Promise<void> {
@ -38,7 +38,7 @@ export class ActivePaymentMethodManager extends BaseUpdateStatusManager<PaymentM
return [ return [
{ {
topic: PaymentMethodChangeStatusEvent, topic: PaymentMethodChangeStatusEvent,
data: this.data, data: this.result,
}, },
]; ];
} }

View File

@ -11,7 +11,7 @@ import { PaymentMethodChangeStatusEvent } from '../../entities/event/payment-met
@Injectable() @Injectable()
export class ConfirmPaymentMethodManager extends BaseUpdateStatusManager<PaymentMethodEntity> { export class ConfirmPaymentMethodManager extends BaseUpdateStatusManager<PaymentMethodEntity> {
getResult(): string { getResult(): string {
return `Success active data ${this.result.account_name}`; return `Success active data ${ this.result.account_name }`;
} }
async validateProcess(): Promise<void> { async validateProcess(): Promise<void> {
@ -38,7 +38,7 @@ export class ConfirmPaymentMethodManager extends BaseUpdateStatusManager<Payment
return [ return [
{ {
topic: PaymentMethodChangeStatusEvent, topic: PaymentMethodChangeStatusEvent,
data: this.data, data: this.result,
}, },
]; ];
} }

View File

@ -11,7 +11,7 @@ import { PaymentMethodChangeStatusEvent } from '../../entities/event/payment-met
@Injectable() @Injectable()
export class InactivePaymentMethodManager extends BaseUpdateStatusManager<PaymentMethodEntity> { export class InactivePaymentMethodManager extends BaseUpdateStatusManager<PaymentMethodEntity> {
getResult(): string { getResult(): string {
return `Success inactive data ${this.result.account_name}`; return `Success inactive data ${ this.result.account_name }`;
} }
async validateProcess(): Promise<void> { async validateProcess(): Promise<void> {
@ -38,7 +38,7 @@ export class InactivePaymentMethodManager extends BaseUpdateStatusManager<Paymen
return [ return [
{ {
topic: PaymentMethodChangeStatusEvent, topic: PaymentMethodChangeStatusEvent,
data: this.data, data: this.result,
}, },
]; ];
} }

View File

@ -11,7 +11,7 @@ import { VipCategoryChangeStatusEvent } from '../../entities/event/vip-category-
@Injectable() @Injectable()
export class ActiveVipCategoryManager extends BaseUpdateStatusManager<VipCategoryEntity> { export class ActiveVipCategoryManager extends BaseUpdateStatusManager<VipCategoryEntity> {
getResult(): string { getResult(): string {
return `Success active data ${this.result.name}`; return `Success active data ${ this.result.name }`;
} }
async validateProcess(): Promise<void> { async validateProcess(): Promise<void> {
@ -38,7 +38,7 @@ export class ActiveVipCategoryManager extends BaseUpdateStatusManager<VipCategor
return [ return [
{ {
topic: VipCategoryChangeStatusEvent, topic: VipCategoryChangeStatusEvent,
data: this.data, data: this.result,
}, },
]; ];
} }

View File

@ -11,7 +11,7 @@ import { VipCategoryChangeStatusEvent } from '../../entities/event/vip-category-
@Injectable() @Injectable()
export class ConfirmVipCategoryManager extends BaseUpdateStatusManager<VipCategoryEntity> { export class ConfirmVipCategoryManager extends BaseUpdateStatusManager<VipCategoryEntity> {
getResult(): string { getResult(): string {
return `Success active data ${this.result.name}`; return `Success active data ${ this.result.name }`;
} }
async validateProcess(): Promise<void> { async validateProcess(): Promise<void> {
@ -38,7 +38,7 @@ export class ConfirmVipCategoryManager extends BaseUpdateStatusManager<VipCatego
return [ return [
{ {
topic: VipCategoryChangeStatusEvent, topic: VipCategoryChangeStatusEvent,
data: this.data, data: this.result,
}, },
]; ];
} }

View File

@ -11,7 +11,7 @@ import { VipCategoryChangeStatusEvent } from '../../entities/event/vip-category-
@Injectable() @Injectable()
export class InactiveVipCategoryManager extends BaseUpdateStatusManager<VipCategoryEntity> { export class InactiveVipCategoryManager extends BaseUpdateStatusManager<VipCategoryEntity> {
getResult(): string { getResult(): string {
return `Success inactive data ${this.result.name}`; return `Success inactive data ${ this.result.name }`;
} }
async validateProcess(): Promise<void> { async validateProcess(): Promise<void> {
@ -38,7 +38,7 @@ export class InactiveVipCategoryManager extends BaseUpdateStatusManager<VipCateg
return [ return [
{ {
topic: VipCategoryChangeStatusEvent, topic: VipCategoryChangeStatusEvent,
data: this.data, data: this.result,
}, },
]; ];
} }

View File

@ -39,7 +39,7 @@ export class UpdateVipCategoryManager extends BaseUpdateManager<VipCategoryEntit
return [ return [
{ {
topic: VipCategoryUpdatedEvent, topic: VipCategoryUpdatedEvent,
data: this.data, data: this.result,
}, },
]; ];
} }

View File

@ -11,7 +11,7 @@ import { UserChangeStatusEvent } from '../../entities/event/user-change-status.e
@Injectable() @Injectable()
export class ActiveUserManager extends BaseUpdateStatusManager<UserEntity> { export class ActiveUserManager extends BaseUpdateStatusManager<UserEntity> {
getResult(): string { getResult(): string {
return `Success active data ${this.result.name}`; return `Success active data ${ this.result.name }`;
} }
async validateProcess(): Promise<void> { async validateProcess(): Promise<void> {
@ -38,7 +38,7 @@ export class ActiveUserManager extends BaseUpdateStatusManager<UserEntity> {
return [ return [
{ {
topic: UserChangeStatusEvent, topic: UserChangeStatusEvent,
data: this.data, data: this.result,
}, },
]; ];
} }

View File

@ -11,7 +11,7 @@ import { UserChangeStatusEvent } from '../../entities/event/user-change-status.e
@Injectable() @Injectable()
export class ConfirmUserManager extends BaseUpdateStatusManager<UserEntity> { export class ConfirmUserManager extends BaseUpdateStatusManager<UserEntity> {
getResult(): string { getResult(): string {
return `Success active data ${this.result.name}`; return `Success active data ${ this.result.name }`;
} }
async validateProcess(): Promise<void> { async validateProcess(): Promise<void> {
@ -38,7 +38,7 @@ export class ConfirmUserManager extends BaseUpdateStatusManager<UserEntity> {
return [ return [
{ {
topic: UserChangeStatusEvent, topic: UserChangeStatusEvent,
data: this.data, data: this.result,
}, },
]; ];
} }

View File

@ -31,7 +31,7 @@ export class CreateUserManager extends BaseCreateManager<UserEntity> {
return; return;
} }
async generateConfig(): Promise<void> {} async generateConfig(): Promise<void> { }
get validateRelations(): validateRelations[] { get validateRelations(): validateRelations[] {
return []; return [];

View File

@ -11,7 +11,7 @@ import { UserChangeStatusEvent } from '../../entities/event/user-change-status.e
@Injectable() @Injectable()
export class InactiveUserManager extends BaseUpdateStatusManager<UserEntity> { export class InactiveUserManager extends BaseUpdateStatusManager<UserEntity> {
getResult(): string { getResult(): string {
return `Success inactive data ${this.result.name}`; return `Success inactive data ${ this.result.name }`;
} }
async validateProcess(): Promise<void> { async validateProcess(): Promise<void> {
@ -38,7 +38,7 @@ export class InactiveUserManager extends BaseUpdateStatusManager<UserEntity> {
return [ return [
{ {
topic: UserChangeStatusEvent, topic: UserChangeStatusEvent,
data: this.data, data: this.result,
}, },
]; ];
} }

View File

@ -45,7 +45,7 @@ export class UpdatePasswordUserManager extends BaseUpdateManager<UserEntity> {
return [ return [
{ {
topic: UserUpdatedEvent, topic: UserUpdatedEvent,
data: this.data, data: this.result,
}, },
]; ];
} }

View File

@ -52,7 +52,7 @@ export class UpdateUserManager extends BaseUpdateManager<UserEntity> {
return [ return [
{ {
topic: UserUpdatedEvent, topic: UserUpdatedEvent,
data: this.data, data: this.result,
}, },
]; ];
} }