Compare commits
No commits in common. "development" and "1.4.4-alpha.2" have entirely different histories.
developmen
...
1.4.4-alph
|
@ -46,8 +46,4 @@ SUPERSET_ADMIN_USERNAME=admin
|
||||||
SUPERSET_ADMIN_PASSWORD=admin
|
SUPERSET_ADMIN_PASSWORD=admin
|
||||||
|
|
||||||
WHATSAPP_BUSINESS_ACCOUNT_NUMBER_ID=604883366037548
|
WHATSAPP_BUSINESS_ACCOUNT_NUMBER_ID=604883366037548
|
||||||
WHATSAPP_BUSINESS_ACCESS_TOKEN=EAAINOvRRiEEBO9yQsYDnYtjHZB7q1nZCwbBpRcxIGMDWajKZBtmWxNRKvPYkS95KQZBsZBOvSFyjiEg5CcCZBZBtaSZApxyV8fiA3cEyVwf7iVZBQP2YCTPRQZArMFeeXbO0uq5TGygmjsIz3M4YxcUHxPzKO4pKxIyxnzcoUZCqCSo1NqQSLVf3a0JyZAwgDXGL55dV
|
WHATSAPP_BUSINESS_ACCESS_TOKEN=EAAINOvRRiEEBO9yQsYDnYtjHZB7q1nZCwbBpRcxIGMDWajKZBtmWxNRKvPYkS95KQZBsZBOvSFyjiEg5CcCZBZBtaSZApxyV8fiA3cEyVwf7iVZBQP2YCTPRQZArMFeeXbO0uq5TGygmjsIz3M4YxcUHxPzKO4pKxIyxnzcoUZCqCSo1NqQSLVf3a0JyZAwgDXGL55dV
|
||||||
|
|
||||||
SETUP_SCHEDULING_KEY=scheduling_key_example
|
|
||||||
|
|
||||||
SKIP_TRANSACTION_FEATURE=false
|
|
|
@ -43,8 +43,4 @@ SUPERSET_ADMIN_USERNAME=admin
|
||||||
SUPERSET_ADMIN_PASSWORD=admin
|
SUPERSET_ADMIN_PASSWORD=admin
|
||||||
|
|
||||||
WHATSAPP_BUSINESS_ACCOUNT_NUMBER_ID=604883366037548
|
WHATSAPP_BUSINESS_ACCOUNT_NUMBER_ID=604883366037548
|
||||||
WHATSAPP_BUSINESS_ACCESS_TOKEN=EAAINOvRRiEEBO9yQsYDnYtjHZB7q1nZCwbBpRcxIGMDWajKZBtmWxNRKvPYkS95KQZBsZBOvSFyjiEg5CcCZBZBtaSZApxyV8fiA3cEyVwf7iVZBQP2YCTPRQZArMFeeXbO0uq5TGygmjsIz3M4YxcUHxPzKO4pKxIyxnzcoUZCqCSo1NqQSLVf3a0JyZAwgDXGL55dV
|
WHATSAPP_BUSINESS_ACCESS_TOKEN=EAAINOvRRiEEBO9yQsYDnYtjHZB7q1nZCwbBpRcxIGMDWajKZBtmWxNRKvPYkS95KQZBsZBOvSFyjiEg5CcCZBZBtaSZApxyV8fiA3cEyVwf7iVZBQP2YCTPRQZArMFeeXbO0uq5TGygmjsIz3M4YxcUHxPzKO4pKxIyxnzcoUZCqCSo1NqQSLVf3a0JyZAwgDXGL55dV
|
||||||
|
|
||||||
SETUP_SCHEDULING_KEY=scheduling_key_example
|
|
||||||
|
|
||||||
SKIP_TRANSACTION_FEATURE=false
|
|
|
@ -49,18 +49,15 @@
|
||||||
"exceljs": "^4.4.0",
|
"exceljs": "^4.4.0",
|
||||||
"fs-extra": "^11.2.0",
|
"fs-extra": "^11.2.0",
|
||||||
"googleapis": "^140.0.0",
|
"googleapis": "^140.0.0",
|
||||||
"gtts": "^0.2.1",
|
|
||||||
"handlebars": "^4.7.8",
|
"handlebars": "^4.7.8",
|
||||||
"mathjs": "^13.0.2",
|
"mathjs": "^13.0.2",
|
||||||
"midtrans-client": "^1.3.1",
|
"midtrans-client": "^1.3.1",
|
||||||
"moment": "^2.30.1",
|
"moment": "^2.30.1",
|
||||||
"moment-timezone": "^0.6.0",
|
|
||||||
"nano": "^10.1.3",
|
"nano": "^10.1.3",
|
||||||
"nodemailer": "^6.9.14",
|
"nodemailer": "^6.9.14",
|
||||||
"pdfmake": "^0.2.10",
|
"pdfmake": "^0.2.10",
|
||||||
"pg": "^8.11.5",
|
"pg": "^8.11.5",
|
||||||
"plop": "^4.0.1",
|
"plop": "^4.0.1",
|
||||||
"qrcode": "^1.5.4",
|
|
||||||
"reflect-metadata": "^0.2.0",
|
"reflect-metadata": "^0.2.0",
|
||||||
"rxjs": "^7.5.0",
|
"rxjs": "^7.5.0",
|
||||||
"typeorm": "^0.3.20",
|
"typeorm": "^0.3.20",
|
||||||
|
@ -73,7 +70,6 @@
|
||||||
"@types/express": "^4.17.13",
|
"@types/express": "^4.17.13",
|
||||||
"@types/jest": "29.5.12",
|
"@types/jest": "29.5.12",
|
||||||
"@types/node": "^20.12.13",
|
"@types/node": "^20.12.13",
|
||||||
"@types/qrcode": "^1.5.5",
|
|
||||||
"@types/supertest": "^2.0.11",
|
"@types/supertest": "^2.0.11",
|
||||||
"@typescript-eslint/eslint-plugin": "^5.0.0",
|
"@typescript-eslint/eslint-plugin": "^5.0.0",
|
||||||
"@typescript-eslint/parser": "^5.0.0",
|
"@typescript-eslint/parser": "^5.0.0",
|
||||||
|
|
|
@ -33,10 +33,7 @@ import { SeasonTypeModel } from './modules/season-related/season-type/data/model
|
||||||
import { TaxModule } from './modules/transaction/tax/tax.module';
|
import { TaxModule } from './modules/transaction/tax/tax.module';
|
||||||
import { TaxModel } from './modules/transaction/tax/data/models/tax.model';
|
import { TaxModel } from './modules/transaction/tax/data/models/tax.model';
|
||||||
import { SalesPriceFormulaModule } from './modules/transaction/sales-price-formula/sales-price-formula.module';
|
import { SalesPriceFormulaModule } from './modules/transaction/sales-price-formula/sales-price-formula.module';
|
||||||
import {
|
import { SalesPriceFormulaModel } from './modules/transaction/sales-price-formula/data/models/sales-price-formula.model';
|
||||||
SalesPriceFormulaModel,
|
|
||||||
TransactionSettingModel,
|
|
||||||
} from './modules/transaction/sales-price-formula/data/models/sales-price-formula.model';
|
|
||||||
import { ProfitShareFormulaModule } from './modules/transaction/profit-share-formula/profit-share-formula.module';
|
import { ProfitShareFormulaModule } from './modules/transaction/profit-share-formula/profit-share-formula.module';
|
||||||
import { PaymentMethodModule } from './modules/transaction/payment-method/payment-method.module';
|
import { PaymentMethodModule } from './modules/transaction/payment-method/payment-method.module';
|
||||||
import { PaymentMethodModel } from './modules/transaction/payment-method/data/models/payment-method.model';
|
import { PaymentMethodModel } from './modules/transaction/payment-method/data/models/payment-method.model';
|
||||||
|
@ -96,21 +93,6 @@ import {
|
||||||
import { ItemQueueModule } from './modules/item-related/item-queue/item-queue.module';
|
import { ItemQueueModule } from './modules/item-related/item-queue/item-queue.module';
|
||||||
import { ItemQueueModel } from './modules/item-related/item-queue/data/models/item-queue.model';
|
import { ItemQueueModel } from './modules/item-related/item-queue/data/models/item-queue.model';
|
||||||
import { QueueBucketModel } from './modules/queue/data/models/queue-bucket.model';
|
import { QueueBucketModel } from './modules/queue/data/models/queue-bucket.model';
|
||||||
import { VerificationModel } from './modules/booking-online/authentication/data/models/verification.model';
|
|
||||||
import { BookingOnlineAuthModule } from './modules/booking-online/authentication/auth.module';
|
|
||||||
import { BookingOrderModule } from './modules/booking-online/order/order.module';
|
|
||||||
import { TimeGroupModule } from './modules/item-related/time-group/time-group.module';
|
|
||||||
import { TimeGroupModel } from './modules/item-related/time-group/data/models/time-group.model';
|
|
||||||
|
|
||||||
import { OtpVerificationModule } from './modules/configuration/otp-verification/otp-verification.module';
|
|
||||||
import { OtpVerificationModel } from './modules/configuration/otp-verification/data/models/otp-verification.model';
|
|
||||||
import { OtpVerifierModel } from './modules/configuration/otp-verification/data/models/otp-verifier.model';
|
|
||||||
import { RescheduleVerificationModel } from './modules/booking-online/order/data/models/reschedule-verification.model';
|
|
||||||
import { OtpCheckerGuard } from './core/guards/domain/otp-checker.guard';
|
|
||||||
import { DataSchedulingModel } from './modules/configuration/data-scheduling/data/models/data-scheduling.model';
|
|
||||||
import { DataSchedulingModule } from './modules/configuration/data-scheduling/data-scheduling.module';
|
|
||||||
import { DataSchedulingDefaultModel } from './modules/configuration/data-scheduling/data/models/data-scheduling-default.model';
|
|
||||||
import { DataSchedulingLogModel } from './modules/configuration/data-scheduling/data/models/data-scheduling-log.model';
|
|
||||||
|
|
||||||
@Module({
|
@Module({
|
||||||
imports: [
|
imports: [
|
||||||
|
@ -136,7 +118,6 @@ import { DataSchedulingLogModel } from './modules/configuration/data-scheduling/
|
||||||
ItemCategoryModel,
|
ItemCategoryModel,
|
||||||
ItemRateModel,
|
ItemRateModel,
|
||||||
ItemQueueModel,
|
ItemQueueModel,
|
||||||
TimeGroupModel,
|
|
||||||
LogModel,
|
LogModel,
|
||||||
LogUserLoginModel,
|
LogUserLoginModel,
|
||||||
NewsModel,
|
NewsModel,
|
||||||
|
@ -156,7 +137,6 @@ import { DataSchedulingLogModel } from './modules/configuration/data-scheduling/
|
||||||
TransactionItemBreakdownModel,
|
TransactionItemBreakdownModel,
|
||||||
TransactionItemTaxModel,
|
TransactionItemTaxModel,
|
||||||
TransactionBreakdownTaxModel,
|
TransactionBreakdownTaxModel,
|
||||||
TransactionSettingModel,
|
|
||||||
UserModel,
|
UserModel,
|
||||||
UserLoginModel,
|
UserLoginModel,
|
||||||
|
|
||||||
|
@ -173,18 +153,6 @@ import { DataSchedulingLogModel } from './modules/configuration/data-scheduling/
|
||||||
QueueItemModel,
|
QueueItemModel,
|
||||||
QueueModel,
|
QueueModel,
|
||||||
QueueBucketModel,
|
QueueBucketModel,
|
||||||
|
|
||||||
// Booking Online
|
|
||||||
VerificationModel,
|
|
||||||
RescheduleVerificationModel,
|
|
||||||
|
|
||||||
OtpVerificationModel,
|
|
||||||
OtpVerifierModel,
|
|
||||||
|
|
||||||
// Data Scheduling
|
|
||||||
DataSchedulingModel,
|
|
||||||
DataSchedulingDefaultModel,
|
|
||||||
DataSchedulingLogModel,
|
|
||||||
],
|
],
|
||||||
synchronize: false,
|
synchronize: false,
|
||||||
}),
|
}),
|
||||||
|
@ -211,7 +179,6 @@ import { DataSchedulingLogModel } from './modules/configuration/data-scheduling/
|
||||||
ItemModule,
|
ItemModule,
|
||||||
ItemRateModule,
|
ItemRateModule,
|
||||||
ItemQueueModule,
|
ItemQueueModule,
|
||||||
TimeGroupModule,
|
|
||||||
|
|
||||||
// transaction
|
// transaction
|
||||||
PaymentMethodModule,
|
PaymentMethodModule,
|
||||||
|
@ -247,18 +214,11 @@ import { DataSchedulingLogModel } from './modules/configuration/data-scheduling/
|
||||||
GateScanModule,
|
GateScanModule,
|
||||||
|
|
||||||
QueueModule,
|
QueueModule,
|
||||||
|
|
||||||
BookingOnlineAuthModule,
|
|
||||||
BookingOrderModule,
|
|
||||||
OtpVerificationModule,
|
|
||||||
DataSchedulingModule,
|
|
||||||
],
|
],
|
||||||
controllers: [],
|
controllers: [],
|
||||||
providers: [
|
providers: [
|
||||||
AuthService,
|
AuthService,
|
||||||
PrivilegeService,
|
PrivilegeService,
|
||||||
OtpCheckerGuard,
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* By default all request from client will protect by JWT
|
* By default all request from client will protect by JWT
|
||||||
* if there is some endpoint/function that does'nt require authentication
|
* if there is some endpoint/function that does'nt require authentication
|
||||||
|
|
|
@ -1,57 +0,0 @@
|
||||||
import {
|
|
||||||
CanActivate,
|
|
||||||
ExecutionContext,
|
|
||||||
Injectable,
|
|
||||||
UnprocessableEntityException,
|
|
||||||
} from '@nestjs/common';
|
|
||||||
import { InjectDataSource } from '@nestjs/typeorm';
|
|
||||||
import { CONNECTION_NAME } from 'src/core/strings/constants/base.constants';
|
|
||||||
import { OtpVerificationModel } from 'src/modules/configuration/otp-verification/data/models/otp-verification.model';
|
|
||||||
import { OtpVerificationEntity } from 'src/modules/configuration/otp-verification/domain/entities/otp-verification.entity';
|
|
||||||
import { DataSource } from 'typeorm';
|
|
||||||
|
|
||||||
@Injectable()
|
|
||||||
export class OtpCheckerGuard implements CanActivate {
|
|
||||||
constructor(
|
|
||||||
@InjectDataSource(CONNECTION_NAME.DEFAULT)
|
|
||||||
protected readonly dataSource: DataSource,
|
|
||||||
) {}
|
|
||||||
|
|
||||||
get otpRepository() {
|
|
||||||
return this.dataSource.getRepository(OtpVerificationModel);
|
|
||||||
}
|
|
||||||
|
|
||||||
async canActivate(context: ExecutionContext): Promise<boolean> {
|
|
||||||
const request = context.switchToHttp().getRequest();
|
|
||||||
const verificationCode = request.headers['x-verification-code'];
|
|
||||||
console.log({ verificationCode });
|
|
||||||
|
|
||||||
if (verificationCode) {
|
|
||||||
const decoded = Buffer.from(verificationCode, 'base64').toString('ascii');
|
|
||||||
const [dataIdentity, otpCode] = decoded.split('|');
|
|
||||||
|
|
||||||
let otpData: OtpVerificationEntity;
|
|
||||||
|
|
||||||
otpData = await this.otpRepository.findOne({
|
|
||||||
where: {
|
|
||||||
otp_code: otpCode,
|
|
||||||
target_id: dataIdentity,
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
if (!otpData) {
|
|
||||||
otpData = await this.otpRepository.findOne({
|
|
||||||
where: {
|
|
||||||
otp_code: otpCode,
|
|
||||||
reference: dataIdentity,
|
|
||||||
},
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
// console.log({ dataIdentity, otpCode, otpData });
|
|
||||||
if (otpData && otpData?.verified_at) return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
throw new UnprocessableEntityException('OTP not verified.');
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -1,66 +0,0 @@
|
||||||
interface OtpServiceEntity {
|
|
||||||
length?: number;
|
|
||||||
}
|
|
||||||
|
|
||||||
export class OtpService {
|
|
||||||
private readonly otpLength: number;
|
|
||||||
|
|
||||||
constructor({ length = 4 }: OtpServiceEntity) {
|
|
||||||
this.otpLength = Math.max(length, 4); // Minimum of 4 digits
|
|
||||||
}
|
|
||||||
|
|
||||||
private hasSequentialDigits(str: string): boolean {
|
|
||||||
for (let i = 0; i < str.length - 1; i++) {
|
|
||||||
const current = parseInt(str[i], 10);
|
|
||||||
const next = parseInt(str[i + 1], 10);
|
|
||||||
if (next === current + 1 || next === current - 1) {
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
private hasRepeatedDigits(str: string): boolean {
|
|
||||||
return str.split('').every((char) => char === str[0]);
|
|
||||||
}
|
|
||||||
|
|
||||||
private isPalindrome(str: string): boolean {
|
|
||||||
return str === str.split('').reverse().join('');
|
|
||||||
}
|
|
||||||
|
|
||||||
private hasPartiallyRepeatedDigits(str: string): boolean {
|
|
||||||
const counts: Record<string, number> = {};
|
|
||||||
for (const char of str) {
|
|
||||||
counts[char] = (counts[char] || 0) + 1;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Reject if any digit appears more than twice
|
|
||||||
return Object.values(counts).some((count) => count > 2);
|
|
||||||
}
|
|
||||||
|
|
||||||
private hasNoMatchLength(str: string) {
|
|
||||||
return str.length !== this.otpLength;
|
|
||||||
}
|
|
||||||
|
|
||||||
private hasStartWithZero(str: string) {
|
|
||||||
return str.split('')[0] === '0';
|
|
||||||
}
|
|
||||||
|
|
||||||
public generateSecureOTP(): string {
|
|
||||||
let otp: string;
|
|
||||||
|
|
||||||
do {
|
|
||||||
otp = Array.from({ length: this.otpLength }, () =>
|
|
||||||
Math.floor(Math.random() * 10).toString(),
|
|
||||||
).join('');
|
|
||||||
} while (
|
|
||||||
this.hasNoMatchLength(otp) ||
|
|
||||||
this.hasSequentialDigits(otp) ||
|
|
||||||
this.hasRepeatedDigits(otp) ||
|
|
||||||
this.isPalindrome(otp) ||
|
|
||||||
this.hasPartiallyRepeatedDigits(otp) ||
|
|
||||||
this.hasStartWithZero(otp)
|
|
||||||
);
|
|
||||||
return otp;
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -52,12 +52,10 @@ export class ValidateRelationHelper<Entity> {
|
||||||
`Failed! this data already connected to ${relation.relation}`;
|
`Failed! this data already connected to ${relation.relation}`;
|
||||||
|
|
||||||
if (relation.singleQuery) {
|
if (relation.singleQuery) {
|
||||||
const relationObject = data[relation.relation] ?? {};
|
|
||||||
const isRelationExist = `${relation.singleQuery[0]}` in relationObject;
|
|
||||||
const relationColumn =
|
const relationColumn =
|
||||||
data[relation.relation]?.[`${relation.singleQuery[0]}`];
|
data[relation.relation]?.[`${relation.singleQuery[0]}`];
|
||||||
if (
|
if (
|
||||||
isRelationExist &&
|
!!relationColumn &&
|
||||||
this.mappingValidator(
|
this.mappingValidator(
|
||||||
relationColumn,
|
relationColumn,
|
||||||
relation.singleQuery[1],
|
relation.singleQuery[1],
|
||||||
|
@ -71,7 +69,6 @@ export class ValidateRelationHelper<Entity> {
|
||||||
}
|
}
|
||||||
|
|
||||||
mappingValidator(column, operator, value) {
|
mappingValidator(column, operator, value) {
|
||||||
const candidates = Array.isArray(value) ? value : [value];
|
|
||||||
switch (operator) {
|
switch (operator) {
|
||||||
case '!=':
|
case '!=':
|
||||||
return column != value;
|
return column != value;
|
||||||
|
@ -79,12 +76,6 @@ export class ValidateRelationHelper<Entity> {
|
||||||
case '==':
|
case '==':
|
||||||
return column == value;
|
return column == value;
|
||||||
|
|
||||||
case 'in':
|
|
||||||
return candidates.includes(column);
|
|
||||||
|
|
||||||
case 'not in':
|
|
||||||
return !candidates.includes(column);
|
|
||||||
|
|
||||||
default:
|
default:
|
||||||
return column == value;
|
return column == value;
|
||||||
}
|
}
|
||||||
|
|
|
@ -28,14 +28,4 @@ export enum MODULE_NAME {
|
||||||
REPORT_SUMMARY = 'report-summary',
|
REPORT_SUMMARY = 'report-summary',
|
||||||
|
|
||||||
QUEUE = 'queue',
|
QUEUE = 'queue',
|
||||||
|
|
||||||
TIME_GROUPS = 'time-groups',
|
|
||||||
OTP_VERIFICATIONS = 'otp-verification',
|
|
||||||
|
|
||||||
OTP_VERIFIER = 'otp-verifier',
|
|
||||||
DATA_SCHEDULING = 'data-scheduling',
|
|
||||||
DATA_SCHEDULING_LOG = 'data-scheduling-log',
|
|
||||||
DATA_SCHEDULING_DEFAULT = 'data-scheduling-default',
|
|
||||||
DATA_SCHEDULING_ACTIVE = 'data-scheduling-active',
|
|
||||||
DATA_SCHEDULING_SETUP = 'data-scheduling-setup',
|
|
||||||
}
|
}
|
||||||
|
|
|
@ -12,7 +12,6 @@ export enum TABLE_NAME {
|
||||||
NEWS = 'news',
|
NEWS = 'news',
|
||||||
PAYMENT_METHOD = 'payment_methods',
|
PAYMENT_METHOD = 'payment_methods',
|
||||||
PRICE_FORMULA = 'price_formulas',
|
PRICE_FORMULA = 'price_formulas',
|
||||||
|
|
||||||
REFUND = 'refunds',
|
REFUND = 'refunds',
|
||||||
REFUND_ITEM = 'refund_items',
|
REFUND_ITEM = 'refund_items',
|
||||||
SEASON_TYPE = 'season_types',
|
SEASON_TYPE = 'season_types',
|
||||||
|
@ -27,8 +26,6 @@ export enum TABLE_NAME {
|
||||||
TRANSACTION_ITEM_TAX = 'transaction_item_taxes',
|
TRANSACTION_ITEM_TAX = 'transaction_item_taxes',
|
||||||
TRANSACTION_ITEM_BREAKDOWN_TAX = 't_breakdown_item_taxes',
|
TRANSACTION_ITEM_BREAKDOWN_TAX = 't_breakdown_item_taxes',
|
||||||
TRANSACTION_DEMOGRAPHY = 'transaction_demographies',
|
TRANSACTION_DEMOGRAPHY = 'transaction_demographies',
|
||||||
TRANSACTION_SETTING = 'api_settings',
|
|
||||||
|
|
||||||
USER = 'users',
|
USER = 'users',
|
||||||
USER_LOGIN = 'users_login',
|
USER_LOGIN = 'users_login',
|
||||||
LOG_USER_LOGIN = 'log_users_login',
|
LOG_USER_LOGIN = 'log_users_login',
|
||||||
|
@ -45,12 +42,4 @@ export enum TABLE_NAME {
|
||||||
QUEUE_TICKET = 'queue_tickets',
|
QUEUE_TICKET = 'queue_tickets',
|
||||||
QUEUE_ITEM = 'queue_items',
|
QUEUE_ITEM = 'queue_items',
|
||||||
QUEUE_BUCKET = 'queue_bucket',
|
QUEUE_BUCKET = 'queue_bucket',
|
||||||
|
|
||||||
TIME_GROUPS = 'time_groups',
|
|
||||||
OTP_VERIFICATIONS = 'otp_verifications',
|
|
||||||
OTP_VERIFIER = 'otp_verifier',
|
|
||||||
|
|
||||||
DATA_SCHEDULING = 'event_scheduling',
|
|
||||||
DATA_SCHEDULING_DEFAULT = 'event_scheduling_default',
|
|
||||||
DATA_SCHEDULING_LOG = 'event_scheduling_log',
|
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,15 +0,0 @@
|
||||||
import { MigrationInterface, QueryRunner } from 'typeorm';
|
|
||||||
|
|
||||||
export class BookingAuthentication1748313715598 implements MigrationInterface {
|
|
||||||
name = 'BookingAuthentication1748313715598';
|
|
||||||
|
|
||||||
public async up(queryRunner: QueryRunner): Promise<void> {
|
|
||||||
await queryRunner.query(
|
|
||||||
`CREATE TABLE "booking_verification" ("id" uuid NOT NULL DEFAULT uuid_generate_v4(), "name" character varying NOT NULL, "phone_number" character varying NOT NULL, "code" character varying, "tried" integer NOT NULL DEFAULT '0', "created_at" bigint NOT NULL DEFAULT EXTRACT(EPOCH FROM NOW()) * 1000, "updated_at" bigint NOT NULL DEFAULT EXTRACT(EPOCH FROM NOW()) * 1000, CONSTRAINT "PK_046e9288c7dd05c7259275d9fc0" PRIMARY KEY ("id"))`,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
public async down(queryRunner: QueryRunner): Promise<void> {
|
|
||||||
await queryRunner.query(`DROP TABLE "booking_verification"`);
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -1,27 +0,0 @@
|
||||||
import { MigrationInterface, QueryRunner } from 'typeorm';
|
|
||||||
|
|
||||||
export class CreateTimeGroupTable1748409891706 implements MigrationInterface {
|
|
||||||
name = 'CreateTimeGroupTable1748409891706';
|
|
||||||
|
|
||||||
public async up(queryRunner: QueryRunner): Promise<void> {
|
|
||||||
await queryRunner.query(
|
|
||||||
`CREATE TYPE "public"."time_groups_status_enum" AS ENUM('active', 'cancel', 'confirmed', 'draft', 'expired', 'inactive', 'partial refund', 'pending', 'proses refund', 'refunded', 'rejected', 'settled', 'waiting')`,
|
|
||||||
);
|
|
||||||
await queryRunner.query(
|
|
||||||
`CREATE TABLE "time_groups" ("id" uuid NOT NULL DEFAULT uuid_generate_v4(), "creator_id" character varying(36), "creator_name" character varying(125), "editor_id" character varying(36), "editor_name" character varying(125), "created_at" bigint NOT NULL, "updated_at" bigint NOT NULL, "status" "public"."time_groups_status_enum" NOT NULL DEFAULT 'draft', "name" character varying NOT NULL, "start_time" TIME NOT NULL, "end_time" TIME NOT NULL, "max_usage_time" TIME NOT NULL, CONSTRAINT "PK_083d02988db7bedfe3b7c869b50" PRIMARY KEY ("id"))`,
|
|
||||||
);
|
|
||||||
await queryRunner.query(`ALTER TABLE "items" ADD "time_group_id" uuid`);
|
|
||||||
await queryRunner.query(
|
|
||||||
`ALTER TABLE "items" ADD CONSTRAINT "FK_f44f222e1808448dca1b6cc4557" FOREIGN KEY ("time_group_id") REFERENCES "time_groups"("id") ON DELETE CASCADE ON UPDATE CASCADE`,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
public async down(queryRunner: QueryRunner): Promise<void> {
|
|
||||||
await queryRunner.query(
|
|
||||||
`ALTER TABLE "items" DROP CONSTRAINT "FK_f44f222e1808448dca1b6cc4557"`,
|
|
||||||
);
|
|
||||||
await queryRunner.query(`ALTER TABLE "items" DROP COLUMN "time_group_id"`);
|
|
||||||
await queryRunner.query(`DROP TABLE "time_groups"`);
|
|
||||||
await queryRunner.query(`DROP TYPE "public"."time_groups_status_enum"`);
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -1,21 +0,0 @@
|
||||||
import { MigrationInterface, QueryRunner } from 'typeorm';
|
|
||||||
|
|
||||||
export class AddColumnOtpCode1748935417155 implements MigrationInterface {
|
|
||||||
name = 'AddColumnOtpCode1748935417155';
|
|
||||||
|
|
||||||
public async up(queryRunner: QueryRunner): Promise<void> {
|
|
||||||
await queryRunner.query(
|
|
||||||
`ALTER TABLE "vip_codes" ADD "otp_code" character varying`,
|
|
||||||
);
|
|
||||||
await queryRunner.query(
|
|
||||||
`ALTER TABLE "transactions" ADD "otp_code" character varying`,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
public async down(queryRunner: QueryRunner): Promise<void> {
|
|
||||||
await queryRunner.query(
|
|
||||||
`ALTER TABLE "transactions" DROP COLUMN "otp_code"`,
|
|
||||||
);
|
|
||||||
await queryRunner.query(`ALTER TABLE "vip_codes" DROP COLUMN "otp_code"`);
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -1,29 +0,0 @@
|
||||||
import { MigrationInterface, QueryRunner } from 'typeorm';
|
|
||||||
|
|
||||||
export class CreateTableOtpCerifications1749028279580
|
|
||||||
implements MigrationInterface
|
|
||||||
{
|
|
||||||
name = 'CreateTableOtpCerifications1749028279580';
|
|
||||||
|
|
||||||
public async up(queryRunner: QueryRunner): Promise<void> {
|
|
||||||
await queryRunner.query(
|
|
||||||
`CREATE TYPE "public"."otp_verifications_action_type_enum" AS ENUM('CREATE_DISCOUNT', 'CANCEL_TRANSACTION')`,
|
|
||||||
);
|
|
||||||
await queryRunner.query(
|
|
||||||
`CREATE TYPE "public"."otp_verifications_source_enum" AS ENUM('POS', 'WEB')`,
|
|
||||||
);
|
|
||||||
await queryRunner.query(
|
|
||||||
`CREATE TABLE "otp_verifications" ("id" uuid NOT NULL DEFAULT uuid_generate_v4(), "creator_id" character varying(36), "creator_name" character varying(125), "editor_id" character varying(36), "editor_name" character varying(125), "created_at" bigint NOT NULL, "updated_at" bigint NOT NULL, "otp_code" character varying NOT NULL, "action_type" "public"."otp_verifications_action_type_enum" NOT NULL, "target_id" character varying, "reference" character varying, "source" "public"."otp_verifications_source_enum" NOT NULL, "is_used" boolean NOT NULL DEFAULT false, "expired_at" bigint NOT NULL, "verified_at" bigint, CONSTRAINT "PK_91d17e75ac3182dba6701869b39" PRIMARY KEY ("id"))`,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
public async down(queryRunner: QueryRunner): Promise<void> {
|
|
||||||
await queryRunner.query(`DROP TABLE "otp_verifications"`);
|
|
||||||
await queryRunner.query(
|
|
||||||
`DROP TYPE "public"."otp_verifications_source_enum"`,
|
|
||||||
);
|
|
||||||
await queryRunner.query(
|
|
||||||
`DROP TYPE "public"."otp_verifications_action_type_enum"`,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -1,19 +0,0 @@
|
||||||
import { MigrationInterface, QueryRunner } from 'typeorm';
|
|
||||||
|
|
||||||
export class AddColumnIsReplacedOtpVerification1749030419440
|
|
||||||
implements MigrationInterface
|
|
||||||
{
|
|
||||||
name = 'AddColumnIsReplacedOtpVerification1749030419440';
|
|
||||||
|
|
||||||
public async up(queryRunner: QueryRunner): Promise<void> {
|
|
||||||
await queryRunner.query(
|
|
||||||
`ALTER TABLE "otp_verifications" ADD "is_replaced" boolean NOT NULL DEFAULT false`,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
public async down(queryRunner: QueryRunner): Promise<void> {
|
|
||||||
await queryRunner.query(
|
|
||||||
`ALTER TABLE "otp_verifications" DROP COLUMN "is_replaced"`,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -1,15 +0,0 @@
|
||||||
import { MigrationInterface, QueryRunner } from 'typeorm';
|
|
||||||
|
|
||||||
export class AddTableOtpVerifier1749043616622 implements MigrationInterface {
|
|
||||||
name = 'AddTableOtpVerifier1749043616622';
|
|
||||||
|
|
||||||
public async up(queryRunner: QueryRunner): Promise<void> {
|
|
||||||
await queryRunner.query(
|
|
||||||
`CREATE TABLE "otp_verifier" ("id" uuid NOT NULL DEFAULT uuid_generate_v4(), "creator_id" character varying(36), "creator_name" character varying(125), "editor_id" character varying(36), "editor_name" character varying(125), "created_at" bigint NOT NULL, "updated_at" bigint NOT NULL, "name" character varying, "phone_number" character varying NOT NULL, CONSTRAINT "PK_884e2d0873fc589a1bdc477b2ea" PRIMARY KEY ("id"))`,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
public async down(queryRunner: QueryRunner): Promise<void> {
|
|
||||||
await queryRunner.query(`DROP TABLE "otp_verifier"`);
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -1,37 +0,0 @@
|
||||||
import { MigrationInterface, QueryRunner } from 'typeorm';
|
|
||||||
|
|
||||||
export class UpdateEnumOtpActionType1749046285398
|
|
||||||
implements MigrationInterface
|
|
||||||
{
|
|
||||||
name = 'UpdateEnumOtpActionType1749046285398';
|
|
||||||
|
|
||||||
public async up(queryRunner: QueryRunner): Promise<void> {
|
|
||||||
await queryRunner.query(
|
|
||||||
`ALTER TYPE "public"."otp_verifications_action_type_enum" RENAME TO "otp_verifications_action_type_enum_old"`,
|
|
||||||
);
|
|
||||||
await queryRunner.query(
|
|
||||||
`CREATE TYPE "public"."otp_verifications_action_type_enum" AS ENUM('CREATE_DISCOUNT', 'CANCEL_TRANSACTION', 'REJECT_RECONCILIATION')`,
|
|
||||||
);
|
|
||||||
await queryRunner.query(
|
|
||||||
`ALTER TABLE "otp_verifications" ALTER COLUMN "action_type" TYPE "public"."otp_verifications_action_type_enum" USING "action_type"::"text"::"public"."otp_verifications_action_type_enum"`,
|
|
||||||
);
|
|
||||||
await queryRunner.query(
|
|
||||||
`DROP TYPE "public"."otp_verifications_action_type_enum_old"`,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
public async down(queryRunner: QueryRunner): Promise<void> {
|
|
||||||
await queryRunner.query(
|
|
||||||
`CREATE TYPE "public"."otp_verifications_action_type_enum_old" AS ENUM('CREATE_DISCOUNT', 'CANCEL_TRANSACTION')`,
|
|
||||||
);
|
|
||||||
await queryRunner.query(
|
|
||||||
`ALTER TABLE "otp_verifications" ALTER COLUMN "action_type" TYPE "public"."otp_verifications_action_type_enum_old" USING "action_type"::"text"::"public"."otp_verifications_action_type_enum_old"`,
|
|
||||||
);
|
|
||||||
await queryRunner.query(
|
|
||||||
`DROP TYPE "public"."otp_verifications_action_type_enum"`,
|
|
||||||
);
|
|
||||||
await queryRunner.query(
|
|
||||||
`ALTER TYPE "public"."otp_verifications_action_type_enum_old" RENAME TO "otp_verifications_action_type_enum"`,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -1,28 +0,0 @@
|
||||||
import { MigrationInterface, QueryRunner } from 'typeorm';
|
|
||||||
|
|
||||||
export class RescheduleOtp1749524993295 implements MigrationInterface {
|
|
||||||
name = 'RescheduleOtp1749524993295';
|
|
||||||
|
|
||||||
public async up(queryRunner: QueryRunner): Promise<void> {
|
|
||||||
await queryRunner.query(
|
|
||||||
`CREATE TABLE "reschedule_verification" ("id" uuid NOT NULL DEFAULT uuid_generate_v4(), "name" character varying NOT NULL, "phone_number" character varying NOT NULL, "booking_id" character varying NOT NULL, "reschedule_date" character varying NOT NULL, "code" integer NOT NULL, "tried" integer NOT NULL DEFAULT '0', "created_at" bigint NOT NULL DEFAULT EXTRACT(EPOCH FROM NOW()) * 1000, "updated_at" bigint NOT NULL DEFAULT EXTRACT(EPOCH FROM NOW()) * 1000, CONSTRAINT "PK_d4df453337ca12771eb223323d8" PRIMARY KEY ("id"))`,
|
|
||||||
);
|
|
||||||
|
|
||||||
await queryRunner.query(
|
|
||||||
`ALTER TABLE "booking_verification" ALTER COLUMN "created_at" SET DEFAULT EXTRACT(EPOCH FROM NOW()) * 1000`,
|
|
||||||
);
|
|
||||||
await queryRunner.query(
|
|
||||||
`ALTER TABLE "booking_verification" ALTER COLUMN "updated_at" SET DEFAULT EXTRACT(EPOCH FROM NOW()) * 1000`,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
public async down(queryRunner: QueryRunner): Promise<void> {
|
|
||||||
await queryRunner.query(
|
|
||||||
`ALTER TABLE "booking_verification" ALTER COLUMN "updated_at" SET DEFAULT (EXTRACT(epoch FROM now()) * (1000))`,
|
|
||||||
);
|
|
||||||
await queryRunner.query(
|
|
||||||
`ALTER TABLE "booking_verification" ALTER COLUMN "created_at" SET DEFAULT (EXTRACT(epoch FROM now()) * (1000))`,
|
|
||||||
);
|
|
||||||
await queryRunner.query(`DROP TABLE "reschedule_verification"`);
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -1,19 +0,0 @@
|
||||||
import { MigrationInterface, QueryRunner } from 'typeorm';
|
|
||||||
|
|
||||||
export class AddBookingDescriptionToItem1749537252986
|
|
||||||
implements MigrationInterface
|
|
||||||
{
|
|
||||||
name = 'AddBookingDescriptionToItem1749537252986';
|
|
||||||
|
|
||||||
public async up(queryRunner: QueryRunner): Promise<void> {
|
|
||||||
await queryRunner.query(
|
|
||||||
`ALTER TABLE "items" ADD "booking_description" text`,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
public async down(queryRunner: QueryRunner): Promise<void> {
|
|
||||||
await queryRunner.query(
|
|
||||||
`ALTER TABLE "items" DROP COLUMN "booking_description"`,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -1,24 +0,0 @@
|
||||||
import { MigrationInterface, QueryRunner } from 'typeorm';
|
|
||||||
|
|
||||||
export class AddBookingParentToTransaction1749604239749
|
|
||||||
implements MigrationInterface
|
|
||||||
{
|
|
||||||
name = 'AddBookingParentToTransaction1749604239749';
|
|
||||||
|
|
||||||
public async up(queryRunner: QueryRunner): Promise<void> {
|
|
||||||
await queryRunner.query(`ALTER TABLE "transactions" ADD "parent_id" uuid`);
|
|
||||||
|
|
||||||
await queryRunner.query(
|
|
||||||
`ALTER TABLE "transactions" ADD CONSTRAINT "FK_413e95171729ba18cabce1c31e3" FOREIGN KEY ("parent_id") REFERENCES "transactions"("id") ON DELETE NO ACTION ON UPDATE NO ACTION`,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
public async down(queryRunner: QueryRunner): Promise<void> {
|
|
||||||
await queryRunner.query(
|
|
||||||
`ALTER TABLE "transactions" DROP CONSTRAINT "FK_413e95171729ba18cabce1c31e3"`,
|
|
||||||
);
|
|
||||||
await queryRunner.query(
|
|
||||||
`ALTER TABLE "transactions" DROP COLUMN "parent_id"`,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -1,55 +0,0 @@
|
||||||
import { MigrationInterface, QueryRunner } from 'typeorm';
|
|
||||||
|
|
||||||
export class AddEnumOtpActionTypeAndUpdateColumnOtpVerifier1750045520332
|
|
||||||
implements MigrationInterface
|
|
||||||
{
|
|
||||||
name = 'AddEnumOtpActionTypeAndUpdateColumnOtpVerifier1750045520332';
|
|
||||||
|
|
||||||
public async up(queryRunner: QueryRunner): Promise<void> {
|
|
||||||
await queryRunner.query(
|
|
||||||
`ALTER TABLE "otp_verifier" ADD "is_all_action" boolean NOT NULL DEFAULT false`,
|
|
||||||
);
|
|
||||||
await queryRunner.query(
|
|
||||||
`CREATE TYPE "public"."otp_verifier_action_types_enum" AS ENUM('CREATE_DISCOUNT', 'CANCEL_TRANSACTION', 'REJECT_RECONCILIATION', 'ACTIVATE_ITEM', 'ACTIVATE_USER', 'UPDATE_ITEM_PRICE', 'UPDATE_ITEM_DETAILS', 'CONFIRM_TRANSACTION')`,
|
|
||||||
);
|
|
||||||
await queryRunner.query(
|
|
||||||
`ALTER TABLE "otp_verifier" ADD "action_types" "public"."otp_verifier_action_types_enum" array`,
|
|
||||||
);
|
|
||||||
await queryRunner.query(
|
|
||||||
`ALTER TYPE "public"."otp_verifications_action_type_enum" RENAME TO "otp_verifications_action_type_enum_old"`,
|
|
||||||
);
|
|
||||||
await queryRunner.query(
|
|
||||||
`CREATE TYPE "public"."otp_verifications_action_type_enum" AS ENUM('CREATE_DISCOUNT', 'CANCEL_TRANSACTION', 'REJECT_RECONCILIATION', 'ACTIVATE_ITEM', 'ACTIVATE_USER', 'UPDATE_ITEM_PRICE', 'UPDATE_ITEM_DETAILS', 'CONFIRM_TRANSACTION')`,
|
|
||||||
);
|
|
||||||
await queryRunner.query(
|
|
||||||
`ALTER TABLE "otp_verifications" ALTER COLUMN "action_type" TYPE "public"."otp_verifications_action_type_enum" USING "action_type"::"text"::"public"."otp_verifications_action_type_enum"`,
|
|
||||||
);
|
|
||||||
await queryRunner.query(
|
|
||||||
`DROP TYPE "public"."otp_verifications_action_type_enum_old"`,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
public async down(queryRunner: QueryRunner): Promise<void> {
|
|
||||||
await queryRunner.query(
|
|
||||||
`CREATE TYPE "public"."otp_verifications_action_type_enum_old" AS ENUM('CREATE_DISCOUNT', 'CANCEL_TRANSACTION', 'REJECT_RECONCILIATION')`,
|
|
||||||
);
|
|
||||||
await queryRunner.query(
|
|
||||||
`ALTER TABLE "otp_verifications" ALTER COLUMN "action_type" TYPE "public"."otp_verifications_action_type_enum_old" USING "action_type"::"text"::"public"."otp_verifications_action_type_enum_old"`,
|
|
||||||
);
|
|
||||||
await queryRunner.query(
|
|
||||||
`DROP TYPE "public"."otp_verifications_action_type_enum"`,
|
|
||||||
);
|
|
||||||
await queryRunner.query(
|
|
||||||
`ALTER TYPE "public"."otp_verifications_action_type_enum_old" RENAME TO "otp_verifications_action_type_enum"`,
|
|
||||||
);
|
|
||||||
await queryRunner.query(
|
|
||||||
`ALTER TABLE "otp_verifier" DROP COLUMN "action_types"`,
|
|
||||||
);
|
|
||||||
await queryRunner.query(
|
|
||||||
`DROP TYPE "public"."otp_verifier_action_types_enum"`,
|
|
||||||
);
|
|
||||||
await queryRunner.query(
|
|
||||||
`ALTER TABLE "otp_verifier" DROP COLUMN "is_all_action"`,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -1,29 +0,0 @@
|
||||||
import { MigrationInterface, QueryRunner } from 'typeorm';
|
|
||||||
|
|
||||||
export class AddUsageTypeToItem1750319148269 implements MigrationInterface {
|
|
||||||
name = 'AddUsageTypeToItem1750319148269';
|
|
||||||
|
|
||||||
public async up(queryRunner: QueryRunner): Promise<void> {
|
|
||||||
await queryRunner.query(
|
|
||||||
`CREATE TYPE "public"."item_queues_usage_type_enum" AS ENUM('one_time', 'multiple')`,
|
|
||||||
);
|
|
||||||
await queryRunner.query(
|
|
||||||
`ALTER TABLE "item_queues" ADD "usage_type" "public"."item_queues_usage_type_enum" NOT NULL DEFAULT 'one_time'`,
|
|
||||||
);
|
|
||||||
await queryRunner.query(
|
|
||||||
`CREATE TYPE "public"."items_usage_type_enum" AS ENUM('one_time', 'multiple')`,
|
|
||||||
);
|
|
||||||
await queryRunner.query(
|
|
||||||
`ALTER TABLE "items" ADD "usage_type" "public"."items_usage_type_enum" NOT NULL DEFAULT 'one_time'`,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
public async down(queryRunner: QueryRunner): Promise<void> {
|
|
||||||
await queryRunner.query(`ALTER TABLE "items" DROP COLUMN "usage_type"`);
|
|
||||||
await queryRunner.query(`DROP TYPE "public"."items_usage_type_enum"`);
|
|
||||||
await queryRunner.query(
|
|
||||||
`ALTER TABLE "item_queues" DROP COLUMN "usage_type"`,
|
|
||||||
);
|
|
||||||
await queryRunner.query(`DROP TYPE "public"."item_queues_usage_type_enum"`);
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -1,17 +0,0 @@
|
||||||
import { MigrationInterface, QueryRunner } from 'typeorm';
|
|
||||||
|
|
||||||
export class RemoveItemNameUnique1750834308368 implements MigrationInterface {
|
|
||||||
name = 'RemoveItemNameUnique1750834308368';
|
|
||||||
|
|
||||||
public async up(queryRunner: QueryRunner): Promise<void> {
|
|
||||||
await queryRunner.query(
|
|
||||||
`ALTER TABLE "items" DROP CONSTRAINT "UQ_213736582899b3599acaade2cd1"`,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
public async down(queryRunner: QueryRunner): Promise<void> {
|
|
||||||
await queryRunner.query(
|
|
||||||
`ALTER TABLE "items" ADD CONSTRAINT "UQ_213736582899b3599acaade2cd1" UNIQUE ("name")`,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -1,38 +0,0 @@
|
||||||
import { MigrationInterface, QueryRunner } from 'typeorm';
|
|
||||||
|
|
||||||
export class RenamTableConfig1751942902581 implements MigrationInterface {
|
|
||||||
name = 'RenamTableConfig1751942902581';
|
|
||||||
|
|
||||||
public async up(queryRunner: QueryRunner): Promise<void> {
|
|
||||||
await queryRunner.query(
|
|
||||||
`CREATE TABLE "api_settings" ("id" uuid NOT NULL DEFAULT uuid_generate_v4(), "creator_id" character varying(36), "creator_name" character varying(125), "editor_id" character varying(36), "editor_name" character varying(125), "created_at" bigint NOT NULL, "updated_at" bigint NOT NULL, "value" numeric NOT NULL DEFAULT '100', CONSTRAINT "PK_14bbb118ae1b2bd2385186cffb9" PRIMARY KEY ("id"))`,
|
|
||||||
);
|
|
||||||
await queryRunner.query(
|
|
||||||
`CREATE TYPE "public"."event_scheduling_status_enum" AS ENUM('active', 'cancel', 'confirmed', 'draft', 'expired', 'inactive', 'partial refund', 'pending', 'proses refund', 'refunded', 'rejected', 'settled', 'waiting')`,
|
|
||||||
);
|
|
||||||
await queryRunner.query(
|
|
||||||
`CREATE TABLE "event_scheduling" ("id" uuid NOT NULL DEFAULT uuid_generate_v4(), "creator_id" character varying(36), "creator_name" character varying(125), "editor_id" character varying(36), "editor_name" character varying(125), "created_at" bigint NOT NULL, "updated_at" bigint NOT NULL, "status" "public"."event_scheduling_status_enum" NOT NULL DEFAULT 'draft', "name" character varying NOT NULL, "indexing_key" character varying NOT NULL, "schedule_date_from" date NOT NULL, "schedule_date_to" date NOT NULL, CONSTRAINT "PK_a2ccd3f6ab787b0d7e2af09d30c" PRIMARY KEY ("id"))`,
|
|
||||||
);
|
|
||||||
await queryRunner.query(
|
|
||||||
`CREATE TABLE "event_scheduling_default" ("id" uuid NOT NULL DEFAULT uuid_generate_v4(), "creator_id" character varying(36), "creator_name" character varying(125), "editor_id" character varying(36), "editor_name" character varying(125), "created_at" bigint NOT NULL, "updated_at" bigint NOT NULL, "default_value" integer NOT NULL, CONSTRAINT "PK_9caf65330e76243e9f9285ae2e1" PRIMARY KEY ("id"))`,
|
|
||||||
);
|
|
||||||
await queryRunner.query(
|
|
||||||
`ALTER TABLE "api_settings" ADD "key" character varying`,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
public async down(queryRunner: QueryRunner): Promise<void> {
|
|
||||||
await queryRunner.query(`DROP TABLE "event_scheduling_default"`);
|
|
||||||
await queryRunner.query(`DROP TABLE "event_scheduling"`);
|
|
||||||
await queryRunner.query(
|
|
||||||
`DROP TYPE "public"."event_scheduling_status_enum"`,
|
|
||||||
);
|
|
||||||
await queryRunner.query(`DROP TABLE "api_settings"`);
|
|
||||||
await queryRunner.query(
|
|
||||||
`ALTER TABLE "item_bundlings" ADD CONSTRAINT "FK_a50e7abf2caba4d0394f3726b86" FOREIGN KEY ("item_bundling_id") REFERENCES "items"("id") ON DELETE CASCADE ON UPDATE CASCADE`,
|
|
||||||
);
|
|
||||||
await queryRunner.query(
|
|
||||||
`ALTER TABLE "queue_tickets" ADD CONSTRAINT "FK_0e9823b8b7ca9523b3be73878e5" FOREIGN KEY ("order_id") REFERENCES "queue_orders"("id") ON DELETE SET NULL ON UPDATE CASCADE`,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -1,33 +0,0 @@
|
||||||
import { MigrationInterface, QueryRunner } from 'typeorm';
|
|
||||||
|
|
||||||
export class DataSchedulingLog1752146975330 implements MigrationInterface {
|
|
||||||
name = 'DataSchedulingLog1752146975330';
|
|
||||||
|
|
||||||
public async up(queryRunner: QueryRunner): Promise<void> {
|
|
||||||
await queryRunner.query(
|
|
||||||
`CREATE TYPE "public"."event_scheduling_log_status_enum" AS ENUM('active', 'cancel', 'confirmed', 'draft', 'expired', 'inactive', 'partial refund', 'pending', 'proses refund', 'refunded', 'rejected', 'settled', 'waiting')`,
|
|
||||||
);
|
|
||||||
await queryRunner.query(
|
|
||||||
`CREATE TYPE "public"."event_scheduling_log_type_enum" AS ENUM('Default Percentage', 'Data Scheduling')`,
|
|
||||||
);
|
|
||||||
await queryRunner.query(
|
|
||||||
`CREATE TYPE "public"."event_scheduling_log_action_enum" AS ENUM('CREATE', 'UPDATE', 'DELETE', 'CHANGE_STATUS')`,
|
|
||||||
);
|
|
||||||
await queryRunner.query(
|
|
||||||
`CREATE TABLE "event_scheduling_log" ("id" uuid NOT NULL DEFAULT uuid_generate_v4(), "creator_id" character varying(36), "creator_name" character varying(125), "editor_id" character varying(36), "editor_name" character varying(125), "created_at" bigint NOT NULL, "updated_at" bigint NOT NULL, "status" "public"."event_scheduling_log_status_enum" NOT NULL DEFAULT 'draft', "type" "public"."event_scheduling_log_type_enum" NOT NULL, "action" "public"."event_scheduling_log_action_enum" NOT NULL, "log_created_at" bigint NOT NULL, "data_id" character varying, "name" character varying, "indexing_key" character varying, "schedule_date_from" date, "schedule_date_to" date, "default_value" integer, "description" text, CONSTRAINT "PK_984247db566636baacab18f593a" PRIMARY KEY ("id"))`,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
public async down(queryRunner: QueryRunner): Promise<void> {
|
|
||||||
await queryRunner.query(`DROP TABLE "event_scheduling_log"`);
|
|
||||||
await queryRunner.query(
|
|
||||||
`DROP TYPE "public"."event_scheduling_log_action_enum"`,
|
|
||||||
);
|
|
||||||
await queryRunner.query(
|
|
||||||
`DROP TYPE "public"."event_scheduling_log_type_enum"`,
|
|
||||||
);
|
|
||||||
await queryRunner.query(
|
|
||||||
`DROP TYPE "public"."event_scheduling_log_status_enum"`,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -1,25 +0,0 @@
|
||||||
import { CONNECTION_NAME } from 'src/core/strings/constants/base.constants';
|
|
||||||
|
|
||||||
import { ConfigModule } from '@nestjs/config';
|
|
||||||
import { Module } from '@nestjs/common';
|
|
||||||
import { VerificationModel } from './data/models/verification.model';
|
|
||||||
import { TypeOrmModule } from '@nestjs/typeorm';
|
|
||||||
import { BookingAuthenticationController } from './infrastructure/controllers/booking-authentication.controller';
|
|
||||||
import { VerificationService } from './data/services/verification.service';
|
|
||||||
import { JwtModule } from '@nestjs/jwt';
|
|
||||||
import { JWT_EXPIRED } from 'src/core/sessions/constants';
|
|
||||||
import { JWT_SECRET } from 'src/core/sessions/constants';
|
|
||||||
@Module({
|
|
||||||
imports: [
|
|
||||||
ConfigModule.forRoot(),
|
|
||||||
TypeOrmModule.forFeature([VerificationModel], CONNECTION_NAME.DEFAULT),
|
|
||||||
|
|
||||||
JwtModule.register({
|
|
||||||
secret: JWT_SECRET,
|
|
||||||
signOptions: { expiresIn: JWT_EXPIRED },
|
|
||||||
}),
|
|
||||||
],
|
|
||||||
controllers: [BookingAuthenticationController],
|
|
||||||
providers: [VerificationService],
|
|
||||||
})
|
|
||||||
export class BookingOnlineAuthModule {}
|
|
|
@ -1,29 +0,0 @@
|
||||||
import { Column, Entity, PrimaryGeneratedColumn } from 'typeorm';
|
|
||||||
import { BookingVerification } from '../../domain/entities/booking-verification.entity';
|
|
||||||
@Entity('booking_verification')
|
|
||||||
export class VerificationModel implements BookingVerification {
|
|
||||||
@PrimaryGeneratedColumn('uuid')
|
|
||||||
id: string;
|
|
||||||
|
|
||||||
@Column()
|
|
||||||
name: string;
|
|
||||||
|
|
||||||
@Column()
|
|
||||||
phone_number: string;
|
|
||||||
|
|
||||||
@Column({ nullable: true })
|
|
||||||
code?: string;
|
|
||||||
|
|
||||||
@Column({ default: 0 })
|
|
||||||
tried: number;
|
|
||||||
|
|
||||||
@Column({ type: 'bigint', default: () => 'EXTRACT(EPOCH FROM NOW()) * 1000' })
|
|
||||||
created_at: number;
|
|
||||||
|
|
||||||
@Column({
|
|
||||||
type: 'bigint',
|
|
||||||
default: () => 'EXTRACT(EPOCH FROM NOW()) * 1000',
|
|
||||||
onUpdate: 'EXTRACT(EPOCH FROM NOW()) * 1000',
|
|
||||||
})
|
|
||||||
updated_at: number;
|
|
||||||
}
|
|
|
@ -1,110 +0,0 @@
|
||||||
import { InjectRepository } from '@nestjs/typeorm';
|
|
||||||
import { Repository } from 'typeorm';
|
|
||||||
import { VerificationModel } from '../models/verification.model';
|
|
||||||
import { BookingVerification } from '../../domain/entities/booking-verification.entity';
|
|
||||||
import { UnprocessableEntityException } from '@nestjs/common';
|
|
||||||
import { JwtService } from '@nestjs/jwt';
|
|
||||||
import { WhatsappService } from 'src/services/whatsapp/whatsapp.service';
|
|
||||||
export class VerificationService {
|
|
||||||
constructor(
|
|
||||||
@InjectRepository(VerificationModel)
|
|
||||||
private readonly verificationRepository: Repository<VerificationModel>,
|
|
||||||
private readonly jwtService: JwtService,
|
|
||||||
) {}
|
|
||||||
|
|
||||||
maxAttempts = 3;
|
|
||||||
expiredTime = 5 * 60 * 1000;
|
|
||||||
expiredTimeRegister = 1 * 60 * 1000;
|
|
||||||
|
|
||||||
async generateToken(payload: BookingVerification) {
|
|
||||||
return this.jwtService.sign({
|
|
||||||
phone_number: payload.phone_number,
|
|
||||||
name: payload.name,
|
|
||||||
created_at: payload.created_at,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
async register(data: BookingVerification) {
|
|
||||||
const isProduction = process.env.NODE_ENV === 'true';
|
|
||||||
const currentTime = Math.floor(Date.now()); // current time in seconds
|
|
||||||
|
|
||||||
// Generate a 4 digit OTP code
|
|
||||||
const otpCode = Math.floor(1000 + Math.random() * 9000).toString();
|
|
||||||
|
|
||||||
let verification = await this.verificationRepository.findOne({
|
|
||||||
where: { phone_number: data.phone_number },
|
|
||||||
});
|
|
||||||
|
|
||||||
if (
|
|
||||||
isProduction &&
|
|
||||||
verification.updated_at &&
|
|
||||||
currentTime - verification.updated_at < this.expiredTimeRegister
|
|
||||||
) {
|
|
||||||
throw new UnprocessableEntityException('Please try again in 1 minute');
|
|
||||||
}
|
|
||||||
|
|
||||||
data.code = otpCode;
|
|
||||||
data.tried = 0;
|
|
||||||
data.updated_at = currentTime;
|
|
||||||
|
|
||||||
if (verification) {
|
|
||||||
// Update existing record
|
|
||||||
verification = this.verificationRepository.merge(verification, data);
|
|
||||||
} else {
|
|
||||||
// Create new record
|
|
||||||
verification = this.verificationRepository.create(data);
|
|
||||||
}
|
|
||||||
const payload = await this.verificationRepository.save(verification);
|
|
||||||
|
|
||||||
const notificationService = new WhatsappService();
|
|
||||||
notificationService.sendOtpNotification({
|
|
||||||
phone: data.phone_number,
|
|
||||||
code: otpCode,
|
|
||||||
});
|
|
||||||
|
|
||||||
return payload;
|
|
||||||
}
|
|
||||||
|
|
||||||
async findByPhoneNumber(phoneNumber: string) {
|
|
||||||
return this.verificationRepository.findOne({
|
|
||||||
where: { phone_number: phoneNumber },
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
async verify(data: BookingVerification): Promise<BookingVerification> {
|
|
||||||
const verification = await this.findByPhoneNumber(data.phone_number);
|
|
||||||
if (!verification) {
|
|
||||||
throw new UnprocessableEntityException('Phone number not found');
|
|
||||||
}
|
|
||||||
|
|
||||||
if (verification.tried >= this.maxAttempts) {
|
|
||||||
throw new UnprocessableEntityException(
|
|
||||||
'Too many attempts, please resend OTP Code',
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (verification.code != data.code) {
|
|
||||||
verification.tried++;
|
|
||||||
await this.verificationRepository.save(verification);
|
|
||||||
throw new UnprocessableEntityException('Invalid verification code');
|
|
||||||
}
|
|
||||||
|
|
||||||
const currentTime = Math.floor(Date.now());
|
|
||||||
if (
|
|
||||||
verification.updated_at &&
|
|
||||||
currentTime - verification.updated_at > this.expiredTime
|
|
||||||
) {
|
|
||||||
throw new UnprocessableEntityException('Verification code expired');
|
|
||||||
}
|
|
||||||
|
|
||||||
return verification;
|
|
||||||
}
|
|
||||||
|
|
||||||
async update(id: string, data: BookingVerification) {
|
|
||||||
return this.verificationRepository.update(id, data);
|
|
||||||
}
|
|
||||||
|
|
||||||
async delete(id: string) {
|
|
||||||
return this.verificationRepository.delete(id);
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -1,9 +0,0 @@
|
||||||
export interface BookingVerification {
|
|
||||||
id: string;
|
|
||||||
name: string;
|
|
||||||
phone_number: string;
|
|
||||||
code?: string;
|
|
||||||
tried?: number;
|
|
||||||
created_at?: number;
|
|
||||||
updated_at?: number;
|
|
||||||
}
|
|
|
@ -1,43 +0,0 @@
|
||||||
import { Controller, Post, Body, Get, Param } from '@nestjs/common';
|
|
||||||
|
|
||||||
import {
|
|
||||||
BookingVerificationDto,
|
|
||||||
VerificationCodeDto,
|
|
||||||
} from '../dto/booking-verification.dto';
|
|
||||||
import { VerificationService } from '../../data/services/verification.service';
|
|
||||||
import { Public } from 'src/core/guards/domain/decorators/unprotected.guard';
|
|
||||||
import { ApiTags } from '@nestjs/swagger';
|
|
||||||
|
|
||||||
@ApiTags('Booking Authentication')
|
|
||||||
@Public()
|
|
||||||
@Controller('v1/booking-authentication')
|
|
||||||
export class BookingAuthenticationController {
|
|
||||||
constructor(
|
|
||||||
private readonly bookingAuthenticationService: VerificationService,
|
|
||||||
) {}
|
|
||||||
|
|
||||||
@Post('verify')
|
|
||||||
async verify(@Body() body: VerificationCodeDto) {
|
|
||||||
const verification = await this.bookingAuthenticationService.verify(body);
|
|
||||||
const token = await this.bookingAuthenticationService.generateToken(
|
|
||||||
verification,
|
|
||||||
);
|
|
||||||
return {
|
|
||||||
message: `Verification successful for ${verification.phone_number}`,
|
|
||||||
token,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
@Post('register')
|
|
||||||
async register(@Body() body: BookingVerificationDto) {
|
|
||||||
const verification = await this.bookingAuthenticationService.register(body);
|
|
||||||
return {
|
|
||||||
message: `Verification code sent to ${verification.phone_number}`,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
@Get('get-by-phone/:phone_number')
|
|
||||||
async getByPhoneNumber(@Param('phone_number') phone_number: string) {
|
|
||||||
return this.bookingAuthenticationService.findByPhoneNumber(phone_number);
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -1,67 +0,0 @@
|
||||||
import { BookingVerification } from '../../domain/entities/booking-verification.entity';
|
|
||||||
import { IsString, IsNotEmpty, Matches } from 'class-validator';
|
|
||||||
import { ApiProperty } from '@nestjs/swagger';
|
|
||||||
|
|
||||||
export class BookingVerificationDto implements BookingVerification {
|
|
||||||
id: string;
|
|
||||||
|
|
||||||
@ApiProperty({
|
|
||||||
type: String,
|
|
||||||
required: true,
|
|
||||||
example: 'John Doe',
|
|
||||||
description: 'Name of the person booking',
|
|
||||||
})
|
|
||||||
@IsString()
|
|
||||||
@IsNotEmpty()
|
|
||||||
name: string;
|
|
||||||
|
|
||||||
@ApiProperty({
|
|
||||||
type: String,
|
|
||||||
required: true,
|
|
||||||
example: '628123456789',
|
|
||||||
description: 'Phone number containing only numeric characters',
|
|
||||||
})
|
|
||||||
@IsString()
|
|
||||||
@IsNotEmpty()
|
|
||||||
@Matches(/^\d+$/, {
|
|
||||||
message: 'phone_number must contain only numeric characters',
|
|
||||||
})
|
|
||||||
phone_number: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
export class VerificationCodeDto implements BookingVerification {
|
|
||||||
id: string;
|
|
||||||
|
|
||||||
@ApiProperty({
|
|
||||||
type: String,
|
|
||||||
required: true,
|
|
||||||
example: 'John Doe',
|
|
||||||
description: 'Name of the person booking',
|
|
||||||
})
|
|
||||||
@IsString()
|
|
||||||
@IsNotEmpty()
|
|
||||||
name: string;
|
|
||||||
|
|
||||||
@ApiProperty({
|
|
||||||
type: String,
|
|
||||||
required: true,
|
|
||||||
example: '628123456789',
|
|
||||||
description: 'Phone number containing only numeric characters',
|
|
||||||
})
|
|
||||||
@IsString()
|
|
||||||
@IsNotEmpty()
|
|
||||||
@Matches(/^\d+$/, {
|
|
||||||
message: 'phone_number must contain only numeric characters',
|
|
||||||
})
|
|
||||||
phone_number: string;
|
|
||||||
|
|
||||||
@ApiProperty({
|
|
||||||
type: String,
|
|
||||||
required: true,
|
|
||||||
example: '1234',
|
|
||||||
description: 'Verification code',
|
|
||||||
})
|
|
||||||
@IsString()
|
|
||||||
@IsNotEmpty()
|
|
||||||
code?: string;
|
|
||||||
}
|
|
|
@ -1,9 +0,0 @@
|
||||||
export function generateOtp(digits = 4): number {
|
|
||||||
if (digits < 1) {
|
|
||||||
throw new Error('OTP digits must be at least 1');
|
|
||||||
}
|
|
||||||
const min = Math.pow(10, digits - 1);
|
|
||||||
const max = Math.pow(10, digits) - 1;
|
|
||||||
const otp = Math.floor(Math.random() * (max - min + 1)) + min;
|
|
||||||
return otp;
|
|
||||||
}
|
|
|
@ -1,36 +0,0 @@
|
||||||
import { Column, Entity, PrimaryGeneratedColumn } from 'typeorm';
|
|
||||||
import { RescheduleVerification } from '../../domain/entities/reschedule-verification.entity';
|
|
||||||
|
|
||||||
@Entity('reschedule_verification')
|
|
||||||
export class RescheduleVerificationModel implements RescheduleVerification {
|
|
||||||
@PrimaryGeneratedColumn('uuid')
|
|
||||||
id: string;
|
|
||||||
|
|
||||||
@Column()
|
|
||||||
name: string;
|
|
||||||
|
|
||||||
@Column()
|
|
||||||
phone_number: string;
|
|
||||||
|
|
||||||
@Column()
|
|
||||||
booking_id: string;
|
|
||||||
|
|
||||||
@Column()
|
|
||||||
reschedule_date: string;
|
|
||||||
|
|
||||||
@Column()
|
|
||||||
code: number;
|
|
||||||
|
|
||||||
@Column({ default: 0 })
|
|
||||||
tried: number;
|
|
||||||
|
|
||||||
@Column({ type: 'bigint', default: () => 'EXTRACT(EPOCH FROM NOW()) * 1000' })
|
|
||||||
created_at: number;
|
|
||||||
|
|
||||||
@Column({
|
|
||||||
type: 'bigint',
|
|
||||||
default: () => 'EXTRACT(EPOCH FROM NOW()) * 1000',
|
|
||||||
onUpdate: 'EXTRACT(EPOCH FROM NOW()) * 1000',
|
|
||||||
})
|
|
||||||
updated_at: number;
|
|
||||||
}
|
|
|
@ -1,16 +0,0 @@
|
||||||
export interface RescheduleVerification {
|
|
||||||
id: string;
|
|
||||||
name: string;
|
|
||||||
phone_number: string;
|
|
||||||
booking_id: string;
|
|
||||||
reschedule_date: string;
|
|
||||||
code: number;
|
|
||||||
tried?: number;
|
|
||||||
created_at?: number;
|
|
||||||
updated_at?: number;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface RescheduleRequest {
|
|
||||||
booking_id: string;
|
|
||||||
reschedule_date: string;
|
|
||||||
}
|
|
|
@ -1,67 +0,0 @@
|
||||||
import { Injectable } from '@nestjs/common';
|
|
||||||
import { RelationParam } from 'src/core/modules/domain/entities/base-filter.entity';
|
|
||||||
import { PaginationResponse } from 'src/core/response/domain/ok-response.interface';
|
|
||||||
import { ItemEntity } from 'src/modules/item-related/item/domain/entities/item.entity';
|
|
||||||
import { IndexItemManager } from 'src/modules/item-related/item/domain/usecases/managers/index-item.manager';
|
|
||||||
import { SelectQueryBuilder } from 'typeorm';
|
|
||||||
|
|
||||||
@Injectable()
|
|
||||||
export class BookingItemManager extends IndexItemManager {
|
|
||||||
get relations(): RelationParam {
|
|
||||||
return {
|
|
||||||
// relation only join (for query purpose)
|
|
||||||
joinRelations: [],
|
|
||||||
|
|
||||||
// relation join and select (relasi yang ingin ditampilkan),
|
|
||||||
selectRelations: [
|
|
||||||
'item_category',
|
|
||||||
'bundling_items',
|
|
||||||
'tenant',
|
|
||||||
'time_group',
|
|
||||||
'item_rates',
|
|
||||||
],
|
|
||||||
|
|
||||||
// relation yang hanya ingin dihitung (akan return number)
|
|
||||||
countRelations: [],
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
get selects(): string[] {
|
|
||||||
const parent = super.selects;
|
|
||||||
return [
|
|
||||||
...parent,
|
|
||||||
`${this.tableName}.image_url`,
|
|
||||||
'item_rates.id',
|
|
||||||
'item_rates.price',
|
|
||||||
'item_rates.season_period_id',
|
|
||||||
];
|
|
||||||
}
|
|
||||||
|
|
||||||
getResult(): PaginationResponse<ItemEntity> {
|
|
||||||
const result = super.getResult();
|
|
||||||
const { data, total } = result;
|
|
||||||
const hasRates = (this.filterParam.season_period_ids?.length ?? 0) > 0;
|
|
||||||
const items = data.map((item) => {
|
|
||||||
const currentRate = item.item_rates.find((rate) =>
|
|
||||||
this.filterParam.season_period_ids?.includes(rate.season_period_id),
|
|
||||||
);
|
|
||||||
const { item_rates, ...rest } = item;
|
|
||||||
const rate = currentRate?.['price'] ?? rest.base_price;
|
|
||||||
return {
|
|
||||||
...rest,
|
|
||||||
base_price: hasRates ? rate : rest.base_price,
|
|
||||||
};
|
|
||||||
});
|
|
||||||
return { total, data: items };
|
|
||||||
}
|
|
||||||
|
|
||||||
setQueryFilter(
|
|
||||||
queryBuilder: SelectQueryBuilder<ItemEntity>,
|
|
||||||
): SelectQueryBuilder<ItemEntity> {
|
|
||||||
const query = super.setQueryFilter(queryBuilder);
|
|
||||||
|
|
||||||
query.andWhere(`${this.tableName}.status = 'active'`);
|
|
||||||
|
|
||||||
return query;
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -1,64 +0,0 @@
|
||||||
import { HttpStatus } from '@nestjs/common';
|
|
||||||
import { UnprocessableEntityException } from '@nestjs/common';
|
|
||||||
import { STATUS } from 'src/core/strings/constants/base.constants';
|
|
||||||
import { TransactionType } from 'src/modules/transaction/transaction/constants';
|
|
||||||
import { CreateTransactionManager } from 'src/modules/transaction/transaction/domain/usecases/managers/create-transaction.manager';
|
|
||||||
import { generateInvoiceCodeHelper } from 'src/modules/transaction/transaction/domain/usecases/managers/helpers/generate-invoice-code.helper';
|
|
||||||
import { mappingRevertTransaction } from 'src/modules/transaction/transaction/domain/usecases/managers/helpers/mapping-transaction.helper';
|
|
||||||
import { WhatsappService } from 'src/services/whatsapp/whatsapp.service';
|
|
||||||
import { v4 as uuidv4 } from 'uuid';
|
|
||||||
|
|
||||||
export class CreateBookingManager extends CreateTransactionManager {
|
|
||||||
async beforeProcess(): Promise<void> {
|
|
||||||
mappingRevertTransaction(this.data, TransactionType.ONLINE);
|
|
||||||
|
|
||||||
const id = uuidv4();
|
|
||||||
const invoiceCode = await generateInvoiceCodeHelper(
|
|
||||||
this.dataService,
|
|
||||||
'BOOK',
|
|
||||||
);
|
|
||||||
|
|
||||||
try {
|
|
||||||
const { token, redirect_url } = await this.dataServiceFirstOpt.create({
|
|
||||||
...this.data,
|
|
||||||
id,
|
|
||||||
});
|
|
||||||
Object.assign(this.data, {
|
|
||||||
payment_midtrans_token: token,
|
|
||||||
payment_midtrans_url: redirect_url,
|
|
||||||
});
|
|
||||||
} catch (error) {
|
|
||||||
console.log({ error });
|
|
||||||
throw new UnprocessableEntityException({
|
|
||||||
statusCode: HttpStatus.UNPROCESSABLE_ENTITY,
|
|
||||||
message: `Gagal! transaksi telah terbuat, silahkan periksa email untuk melanjutkan pembayaran`,
|
|
||||||
error: 'Unprocessable Entity',
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
Object.assign(this.data, {
|
|
||||||
id,
|
|
||||||
invoice_code: invoiceCode,
|
|
||||||
status: STATUS.PENDING,
|
|
||||||
invoice_date: new Date(),
|
|
||||||
});
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
async afterProcess(): Promise<void> {
|
|
||||||
const whatsapp = new WhatsappService();
|
|
||||||
console.log(`/snap/v4/redirection/${this.data.payment_midtrans_token}`);
|
|
||||||
console.log(this.data.payment_midtrans_url);
|
|
||||||
await whatsapp.bookingRegister(
|
|
||||||
{
|
|
||||||
phone: this.data.customer_phone,
|
|
||||||
code: this.data.invoice_code,
|
|
||||||
name: this.data.customer_name,
|
|
||||||
time: this.data.booking_date,
|
|
||||||
id: this.data.id,
|
|
||||||
},
|
|
||||||
this.data.payment_total,
|
|
||||||
`snap/v4/redirection/${this.data.payment_midtrans_token}`,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -1,115 +0,0 @@
|
||||||
import { Injectable, UnprocessableEntityException } from '@nestjs/common';
|
|
||||||
import { InjectRepository } from '@nestjs/typeorm';
|
|
||||||
import { Repository } from 'typeorm';
|
|
||||||
import { RescheduleVerificationModel } from '../../../data/models/reschedule-verification.model';
|
|
||||||
import {
|
|
||||||
RescheduleRequest,
|
|
||||||
RescheduleVerification,
|
|
||||||
} from '../../entities/reschedule-verification.entity';
|
|
||||||
import { generateOtp } from 'src/modules/booking-online/helpers/generate-otp';
|
|
||||||
import { TransactionReadService } from 'src/modules/transaction/transaction/data/services/transaction-read.service';
|
|
||||||
import { TransactionEntity } from 'src/modules/transaction/transaction/domain/entities/transaction.entity';
|
|
||||||
import { WhatsappService } from 'src/services/whatsapp/whatsapp.service';
|
|
||||||
|
|
||||||
@Injectable()
|
|
||||||
export class RescheduleVerificationManager {
|
|
||||||
constructor(
|
|
||||||
@InjectRepository(RescheduleVerificationModel)
|
|
||||||
private readonly rescheduleVerificationRepository: Repository<RescheduleVerificationModel>,
|
|
||||||
private readonly transactionService: TransactionReadService,
|
|
||||||
) {}
|
|
||||||
|
|
||||||
async saveVerification(
|
|
||||||
request: RescheduleRequest,
|
|
||||||
): Promise<RescheduleVerificationModel> {
|
|
||||||
try {
|
|
||||||
const otp = generateOtp();
|
|
||||||
const transaction = await this.findDetailByBookingId(request.booking_id);
|
|
||||||
|
|
||||||
if (!transaction) {
|
|
||||||
throw new Error('Transaction not found for the provided booking id');
|
|
||||||
}
|
|
||||||
|
|
||||||
const data: Partial<RescheduleVerification> = {
|
|
||||||
code: otp,
|
|
||||||
booking_id: transaction.id,
|
|
||||||
name: transaction.customer_name,
|
|
||||||
phone_number: transaction.customer_phone,
|
|
||||||
reschedule_date: request.reschedule_date,
|
|
||||||
};
|
|
||||||
|
|
||||||
const existTransaction =
|
|
||||||
await this.rescheduleVerificationRepository.findOne({
|
|
||||||
where: {
|
|
||||||
booking_id: transaction.id,
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
const verification =
|
|
||||||
existTransaction ?? this.rescheduleVerificationRepository.create(data);
|
|
||||||
const result = await this.rescheduleVerificationRepository.save({
|
|
||||||
...verification,
|
|
||||||
code: otp,
|
|
||||||
});
|
|
||||||
|
|
||||||
const whatsapp = new WhatsappService();
|
|
||||||
whatsapp.sendOtpNotification({
|
|
||||||
phone: transaction.customer_phone,
|
|
||||||
code: otp.toString(),
|
|
||||||
});
|
|
||||||
// whatsapp.bookingRescheduleOTP({
|
|
||||||
// phone: transaction.customer_phone,
|
|
||||||
// code: otp.toString(),
|
|
||||||
// name: transaction.customer_name,
|
|
||||||
// time: new Date(request.reschedule_date).getTime(),
|
|
||||||
// id: transaction.id,
|
|
||||||
// });
|
|
||||||
return result;
|
|
||||||
} catch (error) {
|
|
||||||
// You can customize the error handling as needed, e.g., throw HttpException for NestJS
|
|
||||||
throw new UnprocessableEntityException(
|
|
||||||
`Failed to save reschedule verification: ${error.message}`,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async verifyOtp(
|
|
||||||
booking_id: string,
|
|
||||||
code: number,
|
|
||||||
): Promise<RescheduleVerificationModel> {
|
|
||||||
const verification = await this.rescheduleVerificationRepository.findOne({
|
|
||||||
where: { booking_id, code },
|
|
||||||
order: { created_at: 'DESC' },
|
|
||||||
});
|
|
||||||
|
|
||||||
if (!verification) {
|
|
||||||
throw new UnprocessableEntityException({
|
|
||||||
success: false,
|
|
||||||
message: 'Verification code not match',
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
// Optionally, you can implement OTP expiration logic here
|
|
||||||
|
|
||||||
if (verification.code !== code) {
|
|
||||||
// Increment tried count
|
|
||||||
verification.tried = (verification.tried || 0) + 1;
|
|
||||||
await this.rescheduleVerificationRepository.save(verification);
|
|
||||||
throw new UnprocessableEntityException({
|
|
||||||
success: false,
|
|
||||||
message: 'Invalid verification code.',
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
// Optionally, you can mark the verification as used or verified here
|
|
||||||
|
|
||||||
return verification;
|
|
||||||
}
|
|
||||||
|
|
||||||
async findDetailByBookingId(bookingId: string): Promise<TransactionEntity> {
|
|
||||||
const transaction = await this.transactionService.getOneByOptions({
|
|
||||||
where: { id: bookingId },
|
|
||||||
});
|
|
||||||
return transaction;
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -1,90 +0,0 @@
|
||||||
import { Injectable, UnprocessableEntityException } from '@nestjs/common';
|
|
||||||
import { TransactionModel } from 'src/modules/transaction/transaction/data/models/transaction.model';
|
|
||||||
import { STATUS } from 'src/core/strings/constants/base.constants';
|
|
||||||
import { v4 as uuidv4 } from 'uuid';
|
|
||||||
import { TransactionDataService } from 'src/modules/transaction/transaction/data/services/transaction-data.service';
|
|
||||||
import { generateInvoiceCodeHelper } from 'src/modules/transaction/transaction/domain/usecases/managers/helpers/generate-invoice-code.helper';
|
|
||||||
import * as moment from 'moment';
|
|
||||||
import { TransactionItemModel } from 'src/modules/transaction/transaction/data/models/transaction-item.model';
|
|
||||||
import { RescheduleVerificationModel } from '../../../data/models/reschedule-verification.model';
|
|
||||||
import { WhatsappService } from 'src/services/whatsapp/whatsapp.service';
|
|
||||||
|
|
||||||
@Injectable()
|
|
||||||
export class RescheduleManager {
|
|
||||||
constructor(private serviceData: TransactionDataService) {}
|
|
||||||
|
|
||||||
async reschedule(data: RescheduleVerificationModel) {
|
|
||||||
const transaction = await this.serviceData.getTransactionWithReschedule(
|
|
||||||
data.booking_id,
|
|
||||||
);
|
|
||||||
|
|
||||||
const rescheduleDate = moment(data.reschedule_date, 'DD-MM-YYYY');
|
|
||||||
|
|
||||||
const id = uuidv4();
|
|
||||||
const invoiceCode = await generateInvoiceCodeHelper(
|
|
||||||
this.serviceData,
|
|
||||||
'BOOK',
|
|
||||||
);
|
|
||||||
|
|
||||||
const items = this.makeItemZeroPrice(transaction.items);
|
|
||||||
const transactionData = this.makeTransactionZeroPrice(transaction);
|
|
||||||
|
|
||||||
Object.assign(transactionData, {
|
|
||||||
parent_id: transaction.id,
|
|
||||||
id,
|
|
||||||
invoice_code: invoiceCode,
|
|
||||||
status: STATUS.SETTLED,
|
|
||||||
invoice_date: rescheduleDate.format('YYYY-MM-DD'),
|
|
||||||
booking_date: rescheduleDate.format('YYYY-MM-DD'),
|
|
||||||
created_at: moment().unix() * 1000,
|
|
||||||
updated_at: moment().unix() * 1000,
|
|
||||||
items,
|
|
||||||
});
|
|
||||||
|
|
||||||
await this.serviceData.getRepository().save(transactionData);
|
|
||||||
|
|
||||||
const whatsapp = new WhatsappService();
|
|
||||||
whatsapp.rescheduleCreated({
|
|
||||||
id: transactionData.id,
|
|
||||||
name: transactionData.customer_name,
|
|
||||||
phone: transactionData.customer_phone,
|
|
||||||
time: moment(transactionData.invoice_date).unix() * 1000,
|
|
||||||
code: transactionData.invoice_code,
|
|
||||||
});
|
|
||||||
|
|
||||||
return transactionData;
|
|
||||||
}
|
|
||||||
|
|
||||||
private makeItemZeroPrice(items: TransactionItemModel[]) {
|
|
||||||
return items.map((item) => {
|
|
||||||
return {
|
|
||||||
...item,
|
|
||||||
id: uuidv4(),
|
|
||||||
item_price: 0,
|
|
||||||
total_price: 0,
|
|
||||||
total_hpp: 0,
|
|
||||||
total_profit: 0,
|
|
||||||
total_profit_share: 0,
|
|
||||||
payment_total_dpp: 0,
|
|
||||||
payment_total_tax: 0,
|
|
||||||
total_net_price: 0,
|
|
||||||
};
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
private makeTransactionZeroPrice(transaction: TransactionModel) {
|
|
||||||
return {
|
|
||||||
...transaction,
|
|
||||||
payment_sub_total: 0,
|
|
||||||
payment_discount_total: 0,
|
|
||||||
payment_total: 0,
|
|
||||||
payment_total_pay: 0,
|
|
||||||
payment_total_share: 0,
|
|
||||||
payment_total_tax: 0,
|
|
||||||
payment_total_profit: 0,
|
|
||||||
payment_total_net_profit: 0,
|
|
||||||
payment_total_dpp: 0,
|
|
||||||
discount_percentage: 0,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -1,121 +0,0 @@
|
||||||
import { BaseStatusDto } from 'src/core/modules/infrastructure/dto/base-status.dto';
|
|
||||||
import { ApiProperty } from '@nestjs/swagger';
|
|
||||||
import {
|
|
||||||
IsArray,
|
|
||||||
IsNumber,
|
|
||||||
IsObject,
|
|
||||||
IsString,
|
|
||||||
ValidateIf,
|
|
||||||
} from 'class-validator';
|
|
||||||
import { SeasonPeriodEntity } from 'src/modules/season-related/season-period/domain/entities/season-period.entity';
|
|
||||||
import { TransactionItemEntity } from 'src/modules/transaction/transaction/domain/entities/transaction-item.entity';
|
|
||||||
import {
|
|
||||||
TransactionPaymentType,
|
|
||||||
TransactionUserType,
|
|
||||||
} from 'src/modules/transaction/transaction/constants';
|
|
||||||
|
|
||||||
export class TransactionDto extends BaseStatusDto {
|
|
||||||
@ApiProperty({
|
|
||||||
type: Object,
|
|
||||||
required: false,
|
|
||||||
example: {
|
|
||||||
id: 'uuid',
|
|
||||||
season_type: {
|
|
||||||
id: 'uuid',
|
|
||||||
name: 'high season',
|
|
||||||
},
|
|
||||||
},
|
|
||||||
})
|
|
||||||
@IsObject()
|
|
||||||
@ValidateIf((body) => body.season_period)
|
|
||||||
season_period: SeasonPeriodEntity;
|
|
||||||
|
|
||||||
@ApiProperty({
|
|
||||||
type: String,
|
|
||||||
required: true,
|
|
||||||
example: TransactionUserType.GROUP,
|
|
||||||
})
|
|
||||||
@IsString()
|
|
||||||
customer_type: TransactionUserType;
|
|
||||||
|
|
||||||
@ApiProperty({
|
|
||||||
type: String,
|
|
||||||
required: true,
|
|
||||||
example: 'Andika',
|
|
||||||
})
|
|
||||||
@IsString()
|
|
||||||
customer_name: string;
|
|
||||||
|
|
||||||
@ApiProperty({
|
|
||||||
type: String,
|
|
||||||
required: false,
|
|
||||||
example: '0823...',
|
|
||||||
})
|
|
||||||
@ValidateIf((body) => body.customer_phone)
|
|
||||||
customer_phone: string;
|
|
||||||
|
|
||||||
@ApiProperty({
|
|
||||||
type: Date,
|
|
||||||
required: true,
|
|
||||||
example: '2024-01-01',
|
|
||||||
})
|
|
||||||
booking_date: Date;
|
|
||||||
|
|
||||||
@ApiProperty({
|
|
||||||
type: String,
|
|
||||||
required: false,
|
|
||||||
example: TransactionPaymentType.MIDTRANS,
|
|
||||||
})
|
|
||||||
payment_type: TransactionPaymentType;
|
|
||||||
|
|
||||||
@ApiProperty({
|
|
||||||
type: Number,
|
|
||||||
required: true,
|
|
||||||
example: 7000000,
|
|
||||||
})
|
|
||||||
@IsNumber()
|
|
||||||
payment_sub_total: number;
|
|
||||||
|
|
||||||
@ApiProperty({
|
|
||||||
type: Number,
|
|
||||||
required: true,
|
|
||||||
example: 3500000,
|
|
||||||
})
|
|
||||||
@IsNumber()
|
|
||||||
payment_total: number;
|
|
||||||
|
|
||||||
@ApiProperty({
|
|
||||||
type: [Object],
|
|
||||||
required: true,
|
|
||||||
example: [
|
|
||||||
{
|
|
||||||
item: {
|
|
||||||
id: '68aa12f7-2cce-422b-9bae-185eb1343b94',
|
|
||||||
created_at: '1718876384378',
|
|
||||||
status: 'active',
|
|
||||||
name: 'tes',
|
|
||||||
item_type: 'bundling',
|
|
||||||
hpp: '100000',
|
|
||||||
base_price: '100000',
|
|
||||||
limit_type: 'no limit',
|
|
||||||
limit_value: 0,
|
|
||||||
item_category: {
|
|
||||||
id: 'ab15981a-a656-4efc-856c-b2abfbe30979',
|
|
||||||
name: 'Kategori Bundling 2',
|
|
||||||
},
|
|
||||||
bundling_items: [
|
|
||||||
{
|
|
||||||
id: 'bd5a7a38-df25-4203-a1cd-bf94867946b2',
|
|
||||||
name: 'Wahana 21 panjangggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggg',
|
|
||||||
},
|
|
||||||
],
|
|
||||||
tenant: null,
|
|
||||||
},
|
|
||||||
qty: 40,
|
|
||||||
total_price: 4000000,
|
|
||||||
},
|
|
||||||
],
|
|
||||||
})
|
|
||||||
@IsArray()
|
|
||||||
items: TransactionItemEntity[];
|
|
||||||
}
|
|
|
@ -1,47 +0,0 @@
|
||||||
import { IsString, Matches } from 'class-validator';
|
|
||||||
import { RescheduleRequest } from 'src/modules/booking-online/order/domain/entities/reschedule-verification.entity';
|
|
||||||
|
|
||||||
import { ApiProperty } from '@nestjs/swagger';
|
|
||||||
|
|
||||||
export class RescheduleRequestDTO implements RescheduleRequest {
|
|
||||||
@ApiProperty({
|
|
||||||
type: String,
|
|
||||||
required: true,
|
|
||||||
example: '123e4567-e89b-12d3-a456-426614174000',
|
|
||||||
description: 'The unique identifier of the booking',
|
|
||||||
})
|
|
||||||
@IsString()
|
|
||||||
booking_id: string;
|
|
||||||
|
|
||||||
@ApiProperty({
|
|
||||||
type: String,
|
|
||||||
required: true,
|
|
||||||
example: '25-12-2024',
|
|
||||||
description: 'The new date for rescheduling in the format DD-MM-YYYY',
|
|
||||||
})
|
|
||||||
@IsString()
|
|
||||||
@Matches(/^(0[1-9]|[12][0-9]|3[01])-(0[1-9]|1[0-2])-\d{4}$/, {
|
|
||||||
message: 'reschedule_date must be in the format DD-MM-YYYY',
|
|
||||||
})
|
|
||||||
reschedule_date: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
export class RescheduleVerificationOTP {
|
|
||||||
@ApiProperty({
|
|
||||||
type: String,
|
|
||||||
required: true,
|
|
||||||
example: '123e4567-e89b-12d3-a456-426614174000',
|
|
||||||
description: 'The unique identifier of the booking',
|
|
||||||
})
|
|
||||||
@IsString()
|
|
||||||
booking_id: string;
|
|
||||||
|
|
||||||
@ApiProperty({
|
|
||||||
type: String,
|
|
||||||
required: true,
|
|
||||||
example: '123456',
|
|
||||||
description: 'The OTP code sent for verification',
|
|
||||||
})
|
|
||||||
@IsString()
|
|
||||||
code: string;
|
|
||||||
}
|
|
|
@ -1,32 +0,0 @@
|
||||||
import { Controller, Get, Query } from '@nestjs/common';
|
|
||||||
import { ApiTags } from '@nestjs/swagger';
|
|
||||||
import { Public } from 'src/core/guards';
|
|
||||||
import { PaginationResponse } from 'src/core/response/domain/ok-response.interface';
|
|
||||||
import { TABLE_NAME } from 'src/core/strings/constants/table.constants';
|
|
||||||
import { ItemReadService } from 'src/modules/item-related/item/data/services/item-read.service';
|
|
||||||
import { ItemEntity } from 'src/modules/item-related/item/domain/entities/item.entity';
|
|
||||||
import { FilterItemDto } from 'src/modules/item-related/item/infrastructure/dto/filter-item.dto';
|
|
||||||
import { BookingItemManager } from '../domain/usecases/managers/booking-item.manager';
|
|
||||||
|
|
||||||
@ApiTags('Booking Item')
|
|
||||||
@Controller('v1/booking-item')
|
|
||||||
@Public(true)
|
|
||||||
export class ItemController {
|
|
||||||
constructor(
|
|
||||||
private indexManager: BookingItemManager,
|
|
||||||
private serviceData: ItemReadService,
|
|
||||||
) {}
|
|
||||||
|
|
||||||
@Get()
|
|
||||||
async index(
|
|
||||||
@Query() params: FilterItemDto,
|
|
||||||
): Promise<PaginationResponse<ItemEntity>> {
|
|
||||||
params.limit = 1000;
|
|
||||||
params.show_to_booking = true;
|
|
||||||
params.all_item = true;
|
|
||||||
this.indexManager.setFilterParam(params);
|
|
||||||
this.indexManager.setService(this.serviceData, TABLE_NAME.ITEM);
|
|
||||||
await this.indexManager.execute();
|
|
||||||
return this.indexManager.getResult();
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -1,274 +0,0 @@
|
||||||
import {
|
|
||||||
Body,
|
|
||||||
Controller,
|
|
||||||
Get,
|
|
||||||
Param,
|
|
||||||
Post,
|
|
||||||
Res,
|
|
||||||
UnprocessableEntityException,
|
|
||||||
} from '@nestjs/common';
|
|
||||||
import { ApiTags } from '@nestjs/swagger';
|
|
||||||
import { Public } from 'src/core/guards';
|
|
||||||
import { TransactionDto } from './dto/booking-order.dto';
|
|
||||||
import { TransactionEntity } from 'src/modules/transaction/transaction/domain/entities/transaction.entity';
|
|
||||||
import { TransactionDataService } from 'src/modules/transaction/transaction/data/services/transaction-data.service';
|
|
||||||
import { TABLE_NAME } from 'src/core/strings/constants/table.constants';
|
|
||||||
import { MidtransService } from 'src/modules/configuration/midtrans/data/services/midtrans.service';
|
|
||||||
import { CreateBookingManager } from '../domain/usecases/managers/create-booking.manager';
|
|
||||||
import * as QRCode from 'qrcode';
|
|
||||||
import { Gate } from 'src/core/response/domain/decorators/pagination.response';
|
|
||||||
import { Response } from 'express';
|
|
||||||
import {
|
|
||||||
RescheduleRequestDTO,
|
|
||||||
RescheduleVerificationOTP,
|
|
||||||
} from './dto/reschedule.dto';
|
|
||||||
import { RescheduleVerificationManager } from '../domain/usecases/managers/reschedule-verification.manager';
|
|
||||||
import { RescheduleManager } from '../domain/usecases/managers/reschedule.manager';
|
|
||||||
import { STATUS } from 'src/core/strings/constants/base.constants';
|
|
||||||
import * as moment from 'moment';
|
|
||||||
import { WhatsappService } from 'src/services/whatsapp/whatsapp.service';
|
|
||||||
|
|
||||||
@ApiTags('Booking Order')
|
|
||||||
@Controller('v1/booking')
|
|
||||||
@Public(true)
|
|
||||||
export class BookingOrderController {
|
|
||||||
constructor(
|
|
||||||
private createBooking: CreateBookingManager,
|
|
||||||
private serviceData: TransactionDataService,
|
|
||||||
private midtransService: MidtransService,
|
|
||||||
private rescheduleVerification: RescheduleVerificationManager,
|
|
||||||
private rescheduleManager: RescheduleManager,
|
|
||||||
) {}
|
|
||||||
|
|
||||||
@Post()
|
|
||||||
async create(@Body() data: TransactionDto) {
|
|
||||||
const payload: Partial<TransactionEntity> = data;
|
|
||||||
|
|
||||||
this.createBooking.setData(payload as any);
|
|
||||||
this.createBooking.setService(
|
|
||||||
this.serviceData,
|
|
||||||
TABLE_NAME.TRANSACTION,
|
|
||||||
this.midtransService,
|
|
||||||
);
|
|
||||||
await this.createBooking.execute();
|
|
||||||
const result = await this.createBooking.getResult();
|
|
||||||
const {
|
|
||||||
invoice_code,
|
|
||||||
status,
|
|
||||||
payment_midtrans_token,
|
|
||||||
payment_midtrans_url,
|
|
||||||
id,
|
|
||||||
} = result;
|
|
||||||
|
|
||||||
return {
|
|
||||||
id,
|
|
||||||
invoice_code,
|
|
||||||
status,
|
|
||||||
payment_midtrans_token,
|
|
||||||
payment_midtrans_url,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
@Post('reschedule')
|
|
||||||
async reschedule(@Body() data: RescheduleRequestDTO) {
|
|
||||||
const transaction = await this.serviceData.getTransactionWithReschedule(
|
|
||||||
data.booking_id,
|
|
||||||
);
|
|
||||||
|
|
||||||
const today = moment().startOf('day');
|
|
||||||
const rescheduleDate = moment(data.reschedule_date, 'DD-MM-YYYY');
|
|
||||||
const rescheduleDateStartOfDay = rescheduleDate.startOf('day');
|
|
||||||
|
|
||||||
//TODO: validate session period priority
|
|
||||||
|
|
||||||
if (rescheduleDateStartOfDay.isSameOrBefore(today)) {
|
|
||||||
throw new UnprocessableEntityException(
|
|
||||||
'Reschedule date must be in the future',
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!transaction) {
|
|
||||||
throw new UnprocessableEntityException('Transaction not found');
|
|
||||||
}
|
|
||||||
|
|
||||||
if (transaction.status !== STATUS.SETTLED) {
|
|
||||||
throw new UnprocessableEntityException('Transaction is not settled');
|
|
||||||
}
|
|
||||||
|
|
||||||
if (transaction.children_transactions.length > 0) {
|
|
||||||
throw new UnprocessableEntityException('Transaction already rescheduled');
|
|
||||||
}
|
|
||||||
|
|
||||||
if (transaction.parent_id) {
|
|
||||||
throw new UnprocessableEntityException('Transaction is a reschedule');
|
|
||||||
}
|
|
||||||
|
|
||||||
const result = await this.rescheduleVerification.saveVerification(data);
|
|
||||||
const maskedPhoneNumber = result.phone_number.replace(/.(?=.{4})/g, '*');
|
|
||||||
result.phone_number = maskedPhoneNumber;
|
|
||||||
|
|
||||||
return `Verification code sent to ${maskedPhoneNumber}`;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Post('reschedule/verification')
|
|
||||||
async verificationReschedule(@Body() data: RescheduleVerificationOTP) {
|
|
||||||
const result = await this.rescheduleVerification.verifyOtp(
|
|
||||||
data.booking_id,
|
|
||||||
+data.code,
|
|
||||||
);
|
|
||||||
|
|
||||||
const reschedule = await this.rescheduleManager.reschedule(result);
|
|
||||||
const transaction = await this.get(reschedule.id);
|
|
||||||
|
|
||||||
return {
|
|
||||||
id: reschedule.id,
|
|
||||||
phone_number: result.phone_number,
|
|
||||||
name: result.name,
|
|
||||||
reschedule_date: result.reschedule_date,
|
|
||||||
transaction,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
@Get(':id')
|
|
||||||
async get(@Param('id') transactionId: string) {
|
|
||||||
const data = await this.serviceData.getOneByOptions({
|
|
||||||
relations: [
|
|
||||||
'items',
|
|
||||||
'parent_transaction',
|
|
||||||
'items.item',
|
|
||||||
'items.item.time_group',
|
|
||||||
],
|
|
||||||
where: { id: transactionId },
|
|
||||||
});
|
|
||||||
|
|
||||||
const {
|
|
||||||
parent_id,
|
|
||||||
customer_name,
|
|
||||||
customer_phone,
|
|
||||||
booking_date,
|
|
||||||
invoice_code,
|
|
||||||
status,
|
|
||||||
id,
|
|
||||||
items,
|
|
||||||
parent_transaction,
|
|
||||||
} = data;
|
|
||||||
|
|
||||||
let timeGroup = null;
|
|
||||||
|
|
||||||
const usageItems = items.map((item) => {
|
|
||||||
const itemData = item.item;
|
|
||||||
if (itemData.time_group) {
|
|
||||||
const timeGroupData = itemData.time_group;
|
|
||||||
const {
|
|
||||||
id: groupId,
|
|
||||||
name,
|
|
||||||
start_time,
|
|
||||||
end_time,
|
|
||||||
max_usage_time,
|
|
||||||
} = timeGroupData;
|
|
||||||
timeGroup = {
|
|
||||||
id: groupId,
|
|
||||||
name,
|
|
||||||
start_time,
|
|
||||||
end_time,
|
|
||||||
max_usage_time,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
const {
|
|
||||||
id,
|
|
||||||
item_id,
|
|
||||||
item_name,
|
|
||||||
item_price,
|
|
||||||
item_category_name,
|
|
||||||
total_price,
|
|
||||||
total_net_price,
|
|
||||||
qty,
|
|
||||||
qty_remaining,
|
|
||||||
} = item;
|
|
||||||
return {
|
|
||||||
id,
|
|
||||||
item_id,
|
|
||||||
item_name,
|
|
||||||
item_price,
|
|
||||||
item_category_name,
|
|
||||||
total_price,
|
|
||||||
total_net_price,
|
|
||||||
qty,
|
|
||||||
qty_remaining,
|
|
||||||
};
|
|
||||||
});
|
|
||||||
|
|
||||||
// Mask customer_phone with * and keep last 4 numbers
|
|
||||||
let maskedCustomerPhone = customer_phone;
|
|
||||||
if (typeof customer_phone === 'string' && customer_phone.length > 4) {
|
|
||||||
const last4 = customer_phone.slice(-4);
|
|
||||||
maskedCustomerPhone = '*'.repeat(customer_phone.length - 4) + last4;
|
|
||||||
}
|
|
||||||
|
|
||||||
let parentTransaction = undefined;
|
|
||||||
if (parent_transaction) {
|
|
||||||
const {
|
|
||||||
id: parentId,
|
|
||||||
invoice_code: parentInvoiceCode,
|
|
||||||
invoice_date: parentInvoiceDate,
|
|
||||||
} = parent_transaction;
|
|
||||||
parentTransaction = {
|
|
||||||
id: parentId,
|
|
||||||
invoice_code: parentInvoiceCode,
|
|
||||||
invoice_date: parentInvoiceDate,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
return {
|
|
||||||
customer_name,
|
|
||||||
customer_phone: maskedCustomerPhone,
|
|
||||||
booking_date,
|
|
||||||
invoice_code,
|
|
||||||
status,
|
|
||||||
id,
|
|
||||||
is_reschedule: !!parent_id,
|
|
||||||
items: usageItems,
|
|
||||||
time_group: timeGroup,
|
|
||||||
parent: parentTransaction,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
@Gate()
|
|
||||||
@Get('qrcode/:id')
|
|
||||||
async getQRcode(@Param('id') id: string, @Res() res: Response) {
|
|
||||||
console.log(QRCode);
|
|
||||||
const qrData = id;
|
|
||||||
const data = await QRCode.toDataURL(qrData);
|
|
||||||
res.setHeader('Content-Type', 'image/png');
|
|
||||||
const base64Data = data.split(',')[1];
|
|
||||||
const buffer = Buffer.from(base64Data, 'base64');
|
|
||||||
res.send(buffer);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Post('resend-notification/:id')
|
|
||||||
async resendNotification(@Param('id') id: string) {
|
|
||||||
try {
|
|
||||||
const transaction = await this.serviceData.getOneByOptions({
|
|
||||||
where: { id },
|
|
||||||
});
|
|
||||||
|
|
||||||
const whatsappService = new WhatsappService();
|
|
||||||
const formattedDate = moment(transaction.booking_date);
|
|
||||||
const payload = {
|
|
||||||
id: transaction.id,
|
|
||||||
phone: transaction.customer_phone,
|
|
||||||
code: transaction.invoice_code,
|
|
||||||
name: transaction.customer_name,
|
|
||||||
time: formattedDate.valueOf(),
|
|
||||||
};
|
|
||||||
await whatsappService.bookingCreated(payload);
|
|
||||||
return {
|
|
||||||
message: 'Notification sent successfully',
|
|
||||||
};
|
|
||||||
} catch (error) {
|
|
||||||
throw new UnprocessableEntityException({
|
|
||||||
message: 'Failed to send notification',
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -1,38 +0,0 @@
|
||||||
import { CONNECTION_NAME } from 'src/core/strings/constants/base.constants';
|
|
||||||
|
|
||||||
import { ConfigModule } from '@nestjs/config';
|
|
||||||
import { Module } from '@nestjs/common';
|
|
||||||
import { TypeOrmModule } from '@nestjs/typeorm';
|
|
||||||
import { ItemModel } from 'src/modules/item-related/item/data/models/item.model';
|
|
||||||
import { ItemModule } from 'src/modules/item-related/item/item.module';
|
|
||||||
import { ItemController } from './infrastructure/item.controller';
|
|
||||||
import { TransactionModule } from 'src/modules/transaction/transaction/transaction.module';
|
|
||||||
import { BookingOrderController } from './infrastructure/order.controller';
|
|
||||||
import { CreateBookingManager } from './domain/usecases/managers/create-booking.manager';
|
|
||||||
import { MidtransModule } from 'src/modules/configuration/midtrans/midtrans.module';
|
|
||||||
import { CqrsModule } from '@nestjs/cqrs';
|
|
||||||
import { RescheduleVerificationModel } from './data/models/reschedule-verification.model';
|
|
||||||
import { RescheduleVerificationManager } from './domain/usecases/managers/reschedule-verification.manager';
|
|
||||||
import { RescheduleManager } from './domain/usecases/managers/reschedule.manager';
|
|
||||||
import { BookingItemManager } from './domain/usecases/managers/booking-item.manager';
|
|
||||||
@Module({
|
|
||||||
imports: [
|
|
||||||
ConfigModule.forRoot(),
|
|
||||||
TypeOrmModule.forFeature(
|
|
||||||
[ItemModel, RescheduleVerificationModel],
|
|
||||||
CONNECTION_NAME.DEFAULT,
|
|
||||||
),
|
|
||||||
ItemModule,
|
|
||||||
TransactionModule,
|
|
||||||
MidtransModule,
|
|
||||||
CqrsModule,
|
|
||||||
],
|
|
||||||
controllers: [ItemController, BookingOrderController],
|
|
||||||
providers: [
|
|
||||||
CreateBookingManager,
|
|
||||||
RescheduleVerificationManager,
|
|
||||||
RescheduleManager,
|
|
||||||
BookingItemManager,
|
|
||||||
],
|
|
||||||
})
|
|
||||||
export class BookingOrderModule {}
|
|
|
@ -73,14 +73,13 @@ export class LoginAdminQueueManager extends BaseCustomManager<UserEntity> {
|
||||||
message: `Akun anda sudah login di item "${hasLoginAsQueue?.item_name}"`,
|
message: `Akun anda sudah login di item "${hasLoginAsQueue?.item_name}"`,
|
||||||
error: 'Unauthorized',
|
error: 'Unauthorized',
|
||||||
});
|
});
|
||||||
|
} else if (itemLogin && itemLogin.user_id !== this.userLogin.id) {
|
||||||
|
throw new UnauthorizedException({
|
||||||
|
statusCode: HttpStatus.UNAUTHORIZED,
|
||||||
|
message: `"${userLoginItem.name}" masih login sebagai admin antrian `,
|
||||||
|
error: 'Unauthorized',
|
||||||
|
});
|
||||||
}
|
}
|
||||||
// else if (itemLogin && itemLogin.user_id !== this.userLogin.id) {
|
|
||||||
// throw new UnauthorizedException({
|
|
||||||
// statusCode: HttpStatus.UNAUTHORIZED,
|
|
||||||
// message: `"${userLoginItem.name}" masih login sebagai admin antrian `,
|
|
||||||
// error: 'Unauthorized',
|
|
||||||
// });
|
|
||||||
// }
|
|
||||||
|
|
||||||
// * Disini untuk isi token
|
// * Disini untuk isi token
|
||||||
const tokenData = {
|
const tokenData = {
|
||||||
|
|
|
@ -3,6 +3,4 @@ export const DatabaseListen = [
|
||||||
'vip_code',
|
'vip_code',
|
||||||
'pos_activity',
|
'pos_activity',
|
||||||
'pos_cash_activity',
|
'pos_cash_activity',
|
||||||
'time_groups',
|
|
||||||
'api_configuration',
|
|
||||||
];
|
];
|
||||||
|
|
|
@ -52,14 +52,6 @@ import { SeasonPeriodDataService } from 'src/modules/season-related/season-perio
|
||||||
import { SeasonPeriodModel } from 'src/modules/season-related/season-period/data/models/season-period.model';
|
import { SeasonPeriodModel } from 'src/modules/season-related/season-period/data/models/season-period.model';
|
||||||
import { TransactionDemographyModel } from 'src/modules/transaction/transaction/data/models/transaction-demography.model';
|
import { TransactionDemographyModel } from 'src/modules/transaction/transaction/data/models/transaction-demography.model';
|
||||||
import { UserLoginModel } from 'src/modules/user-related/user/data/models/user-login.model';
|
import { UserLoginModel } from 'src/modules/user-related/user/data/models/user-login.model';
|
||||||
import {
|
|
||||||
TimeGroupDeletedHandler,
|
|
||||||
TimeGroupUpdatedHandler,
|
|
||||||
} from './domain/managers/time-group.handle';
|
|
||||||
|
|
||||||
import { DataSchedulingUpdatedHandler } from './domain/managers/data-scheduling.handler';
|
|
||||||
import { DataSchedulingDefaultModel } from '../data-scheduling/data/models/data-scheduling-default.model';
|
|
||||||
import { DataSchedulingModel } from '../data-scheduling/data/models/data-scheduling.model';
|
|
||||||
|
|
||||||
@Module({
|
@Module({
|
||||||
imports: [
|
imports: [
|
||||||
|
@ -75,9 +67,6 @@ import { DataSchedulingModel } from '../data-scheduling/data/models/data-schedul
|
||||||
TransactionTaxModel,
|
TransactionTaxModel,
|
||||||
TransactionItemModel,
|
TransactionItemModel,
|
||||||
TransactionDemographyModel,
|
TransactionDemographyModel,
|
||||||
|
|
||||||
DataSchedulingDefaultModel,
|
|
||||||
DataSchedulingModel,
|
|
||||||
],
|
],
|
||||||
CONNECTION_NAME.DEFAULT,
|
CONNECTION_NAME.DEFAULT,
|
||||||
),
|
),
|
||||||
|
@ -94,10 +83,6 @@ import { DataSchedulingModel } from '../data-scheduling/data/models/data-schedul
|
||||||
VipCodeCreatedHandler,
|
VipCodeCreatedHandler,
|
||||||
VipCategoryDeletedHandler,
|
VipCategoryDeletedHandler,
|
||||||
VipCategoryUpdatedHandler,
|
VipCategoryUpdatedHandler,
|
||||||
|
|
||||||
TimeGroupDeletedHandler,
|
|
||||||
TimeGroupUpdatedHandler,
|
|
||||||
|
|
||||||
SeasonPeriodDeletedHandler,
|
SeasonPeriodDeletedHandler,
|
||||||
SeasonPeriodUpdatedHandler,
|
SeasonPeriodUpdatedHandler,
|
||||||
ItemUpdatedHandler,
|
ItemUpdatedHandler,
|
||||||
|
@ -111,8 +96,6 @@ import { DataSchedulingModel } from '../data-scheduling/data/models/data-schedul
|
||||||
SeasonTypeDeletedHandler,
|
SeasonTypeDeletedHandler,
|
||||||
SeasonTypeUpdatedHandler,
|
SeasonTypeUpdatedHandler,
|
||||||
|
|
||||||
DataSchedulingUpdatedHandler,
|
|
||||||
|
|
||||||
SeasonPeriodDataService,
|
SeasonPeriodDataService,
|
||||||
TransactionDataService,
|
TransactionDataService,
|
||||||
UserDataService,
|
UserDataService,
|
||||||
|
|
|
@ -19,27 +19,24 @@ export class CouchService {
|
||||||
}
|
}
|
||||||
|
|
||||||
async onModuleInit() {
|
async onModuleInit() {
|
||||||
// return;
|
|
||||||
const nano = this.nanoInstance;
|
const nano = this.nanoInstance;
|
||||||
for (const database of DatabaseListen) {
|
for (const database of DatabaseListen) {
|
||||||
const db = nano.db.use(database);
|
const db = nano.db.use(database);
|
||||||
db.changesReader
|
db.changesReader.start({ includeDocs: true }).on('change', (change) => {
|
||||||
.start({ includeDocs: true })
|
Logger.verbose(
|
||||||
.on('change', async (change) => {
|
`Receive Data from ${database}: ${change?.id}`,
|
||||||
Logger.verbose(
|
'CouchService',
|
||||||
`Receive Data from ${database}: ${change?.id}`,
|
);
|
||||||
'CouchService',
|
this.changeDoc(change, database);
|
||||||
);
|
});
|
||||||
await this.changeDoc(change, database);
|
|
||||||
});
|
|
||||||
|
|
||||||
// transaction
|
// transaction
|
||||||
Logger.log(`start listen database ${database}`, 'CouchService');
|
Logger.log(`start listen database ${database}`, 'CouchService');
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private async changeDoc(data, database) {
|
private changeDoc(data, database) {
|
||||||
await this.eventBus.publish(
|
this.eventBus.publish(
|
||||||
new ChangeDocEvent({
|
new ChangeDocEvent({
|
||||||
id: data.id,
|
id: data.id,
|
||||||
database: database,
|
database: database,
|
||||||
|
@ -98,76 +95,4 @@ export class CouchService {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public async totalTodayTransactions(database = 'transaction') {
|
|
||||||
try {
|
|
||||||
const nano = this.nanoInstance;
|
|
||||||
const db = nano.use<any>(database);
|
|
||||||
|
|
||||||
// Get today's start timestamp (midnight)
|
|
||||||
const today = new Date();
|
|
||||||
today.setHours(0, 0, 0, 0);
|
|
||||||
const todayTimestamp = today.getTime();
|
|
||||||
|
|
||||||
// Query for documents created today
|
|
||||||
const selector = {
|
|
||||||
created_at: {
|
|
||||||
$gte: todayTimestamp,
|
|
||||||
},
|
|
||||||
status: 'settled',
|
|
||||||
};
|
|
||||||
|
|
||||||
const result = await db.find({
|
|
||||||
selector: selector,
|
|
||||||
fields: ['_id', 'payment_total_pay'],
|
|
||||||
limit: 10000,
|
|
||||||
});
|
|
||||||
|
|
||||||
return result.docs.reduce(
|
|
||||||
(sum, doc) => sum + (doc.payment_total_pay || 0),
|
|
||||||
0,
|
|
||||||
);
|
|
||||||
} catch (error) {
|
|
||||||
console.log(error);
|
|
||||||
apm.captureError(error);
|
|
||||||
return 0;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
getUnixTimestampLast7Days() {
|
|
||||||
const date = new Date();
|
|
||||||
date.setDate(date.getDate() - 4);
|
|
||||||
date.setHours(0, 0, 0, 0);
|
|
||||||
return date.getTime();
|
|
||||||
}
|
|
||||||
|
|
||||||
public async clearTransactions() {
|
|
||||||
const nano = this.nanoInstance;
|
|
||||||
const transaction = nano.use('transaction');
|
|
||||||
|
|
||||||
const expiredDate = this.getUnixTimestampLast7Days();
|
|
||||||
|
|
||||||
const selectorPayment = {
|
|
||||||
created_at: {
|
|
||||||
$lt: expiredDate,
|
|
||||||
},
|
|
||||||
};
|
|
||||||
|
|
||||||
const transactions = await transaction.find({
|
|
||||||
selector: selectorPayment,
|
|
||||||
fields: ['_id', '_rev'],
|
|
||||||
limit: 100000,
|
|
||||||
});
|
|
||||||
|
|
||||||
const { docs } = transactions;
|
|
||||||
console.log(docs.length);
|
|
||||||
const deletedDocs = {
|
|
||||||
docs: docs.map((doc) => ({
|
|
||||||
_id: doc._id,
|
|
||||||
_rev: doc._rev,
|
|
||||||
_deleted: true,
|
|
||||||
})),
|
|
||||||
};
|
|
||||||
await transaction.bulk(deletedDocs);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,90 +0,0 @@
|
||||||
import { EventsHandler, IEventHandler } from '@nestjs/cqrs';
|
|
||||||
import { CouchService } from '../../data/services/couch.service';
|
|
||||||
import { DataSchedulingDeletedEvent } from 'src/modules/configuration/data-scheduling/domain/entities/event/data-scheduling-deleted.event';
|
|
||||||
import { DataSchedulingChangeStatusEvent } from 'src/modules/configuration/data-scheduling/domain/entities/event/data-scheduling-change-status.event';
|
|
||||||
import { DataSchedulingUpdatedEvent } from 'src/modules/configuration/data-scheduling/domain/entities/event/data-scheduling-updated.event';
|
|
||||||
import { DataSchedulingCreatedEvent } from 'src/modules/configuration/data-scheduling/domain/entities/event/data-scheduling-created.event';
|
|
||||||
import { InjectRepository } from '@nestjs/typeorm';
|
|
||||||
import { DataSchedulingDefaultModel } from 'src/modules/configuration/data-scheduling/data/models/data-scheduling-default.model';
|
|
||||||
import { DataSchedulingModel } from 'src/modules/configuration/data-scheduling/data/models/data-scheduling.model';
|
|
||||||
import { Repository } from 'typeorm';
|
|
||||||
|
|
||||||
import * as momentTz from 'moment-timezone';
|
|
||||||
import { TABLE_NAME } from 'src/core/strings/constants/table.constants';
|
|
||||||
import { DataSchedulingEntity } from 'src/modules/configuration/data-scheduling/domain/entities/data-scheduling.entity';
|
|
||||||
import { decryptionTotal } from 'src/modules/configuration/data-scheduling/infrastructure/helpers';
|
|
||||||
import { Logger } from '@nestjs/common';
|
|
||||||
|
|
||||||
@EventsHandler(
|
|
||||||
DataSchedulingCreatedEvent,
|
|
||||||
DataSchedulingUpdatedEvent,
|
|
||||||
DataSchedulingChangeStatusEvent,
|
|
||||||
DataSchedulingDeletedEvent,
|
|
||||||
)
|
|
||||||
export class DataSchedulingUpdatedHandler implements IEventHandler {
|
|
||||||
private readonly logger = new Logger(DataSchedulingUpdatedHandler.name);
|
|
||||||
private readonly permanentID = 'e6166c86-d85d-43f8-86ad-c9e85a88f68f';
|
|
||||||
private readonly couchTableName = 'api_configuration';
|
|
||||||
|
|
||||||
constructor(
|
|
||||||
private couchService: CouchService,
|
|
||||||
|
|
||||||
@InjectRepository(DataSchedulingDefaultModel)
|
|
||||||
private repository: Repository<DataSchedulingDefaultModel>,
|
|
||||||
|
|
||||||
@InjectRepository(DataSchedulingModel)
|
|
||||||
private repoSchedule: Repository<DataSchedulingModel>,
|
|
||||||
) {}
|
|
||||||
|
|
||||||
async handle() {
|
|
||||||
const activeData = await this.getActiveData();
|
|
||||||
const existData = await this.couchService.getDoc(
|
|
||||||
this.permanentID,
|
|
||||||
this.couchTableName,
|
|
||||||
);
|
|
||||||
if (!existData) {
|
|
||||||
this.logger.verbose('CREATE SCHEDULING CONFIG');
|
|
||||||
await this.couchService.createDoc(
|
|
||||||
{
|
|
||||||
_id: this.permanentID,
|
|
||||||
id: this.permanentID,
|
|
||||||
...activeData,
|
|
||||||
},
|
|
||||||
this.couchTableName,
|
|
||||||
);
|
|
||||||
} else if (existData) {
|
|
||||||
this.logger.verbose('UPDATE SCHEDULING CONFIG');
|
|
||||||
await this.couchService.updateDoc(
|
|
||||||
{
|
|
||||||
_id: this.permanentID,
|
|
||||||
id: this.permanentID,
|
|
||||||
...activeData,
|
|
||||||
},
|
|
||||||
this.couchTableName,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async getActiveData() {
|
|
||||||
const timeZoneWIB = 'Asia/Jakarta';
|
|
||||||
const nowInWIB = momentTz().tz(timeZoneWIB).format('YYYY-MM-DD');
|
|
||||||
const date = nowInWIB;
|
|
||||||
|
|
||||||
const qb = this.repoSchedule.createQueryBuilder(TABLE_NAME.DATA_SCHEDULING);
|
|
||||||
|
|
||||||
const findData: DataSchedulingEntity = await qb
|
|
||||||
.where('status = :status', { status: 'active' })
|
|
||||||
.andWhere('schedule_date_from <= :date', { date: date })
|
|
||||||
.andWhere('schedule_date_to >= :date', { date: date })
|
|
||||||
.getOne();
|
|
||||||
|
|
||||||
if (!findData) {
|
|
||||||
const defaultData = await this.repository
|
|
||||||
.createQueryBuilder(TABLE_NAME.DATA_SCHEDULING_DEFAULT)
|
|
||||||
.getOne();
|
|
||||||
return { value: defaultData?.default_value };
|
|
||||||
}
|
|
||||||
|
|
||||||
return { value: decryptionTotal(findData.indexing_key as string), date };
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -44,12 +44,10 @@ export class ItemUpdatedHandler
|
||||||
'item_category',
|
'item_category',
|
||||||
'bundling_items',
|
'bundling_items',
|
||||||
'bundling_items.item_category',
|
'bundling_items.item_category',
|
||||||
'bundling_items.time_group',
|
|
||||||
'item_rates',
|
'item_rates',
|
||||||
'item_rates.item',
|
'item_rates.item',
|
||||||
'item_rates.season_period',
|
'item_rates.season_period',
|
||||||
'item_rates.season_period.season_type',
|
'item_rates.season_period.season_type',
|
||||||
'time_group',
|
|
||||||
],
|
],
|
||||||
});
|
});
|
||||||
|
|
||||||
|
@ -107,12 +105,10 @@ export class ItemPriceUpdatedHandler
|
||||||
'item_category',
|
'item_category',
|
||||||
'bundling_items',
|
'bundling_items',
|
||||||
'bundling_items.item_category',
|
'bundling_items.item_category',
|
||||||
'bundling_items.time_group',
|
|
||||||
'item_rates',
|
'item_rates',
|
||||||
'item_rates.item',
|
'item_rates.item',
|
||||||
'item_rates.season_period',
|
'item_rates.season_period',
|
||||||
'item_rates.season_period.season_type',
|
'item_rates.season_period.season_type',
|
||||||
'time_group',
|
|
||||||
],
|
],
|
||||||
});
|
});
|
||||||
|
|
||||||
|
@ -150,12 +146,10 @@ export class ItemRateUpdatedHandler
|
||||||
'item_category',
|
'item_category',
|
||||||
'bundling_items',
|
'bundling_items',
|
||||||
'bundling_items.item_category',
|
'bundling_items.item_category',
|
||||||
'bundling_items.time_group',
|
|
||||||
'item_rates',
|
'item_rates',
|
||||||
'item_rates.item',
|
'item_rates.item',
|
||||||
'item_rates.season_period',
|
'item_rates.season_period',
|
||||||
'item_rates.season_period.season_type',
|
'item_rates.season_period.season_type',
|
||||||
'time_group',
|
|
||||||
],
|
],
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|
|
@ -1,65 +0,0 @@
|
||||||
import { EventsHandler, IEventHandler } from '@nestjs/cqrs';
|
|
||||||
import { CouchService } from '../../data/services/couch.service';
|
|
||||||
import { STATUS } from 'src/core/strings/constants/base.constants';
|
|
||||||
import { TimeGroupDeletedEvent } from 'src/modules/item-related/time-group/domain/entities/event/time-group-deleted.event';
|
|
||||||
import { TimeGroupChangeStatusEvent } from 'src/modules/item-related/time-group/domain/entities/event/time-group-change-status.event';
|
|
||||||
import { TimeGroupUpdatedEvent } from 'src/modules/item-related/time-group/domain/entities/event/time-group-updated.event';
|
|
||||||
|
|
||||||
@EventsHandler(TimeGroupDeletedEvent)
|
|
||||||
export class TimeGroupDeletedHandler
|
|
||||||
implements IEventHandler<TimeGroupDeletedEvent>
|
|
||||||
{
|
|
||||||
constructor(private couchService: CouchService) {}
|
|
||||||
|
|
||||||
async handle(event: TimeGroupDeletedEvent) {
|
|
||||||
const data = await this.couchService.deleteDoc(
|
|
||||||
{
|
|
||||||
_id: event.data.id,
|
|
||||||
...event.data.data,
|
|
||||||
},
|
|
||||||
'time_groups',
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@EventsHandler(TimeGroupChangeStatusEvent, TimeGroupUpdatedEvent)
|
|
||||||
export class TimeGroupUpdatedHandler
|
|
||||||
implements IEventHandler<TimeGroupChangeStatusEvent>
|
|
||||||
{
|
|
||||||
constructor(private couchService: CouchService) {}
|
|
||||||
|
|
||||||
async handle(event: TimeGroupChangeStatusEvent) {
|
|
||||||
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,
|
|
||||||
},
|
|
||||||
'time_groups',
|
|
||||||
);
|
|
||||||
} else if (dataOld?.status != data.status) {
|
|
||||||
await this.couchService.deleteDoc(
|
|
||||||
{
|
|
||||||
_id: data.id,
|
|
||||||
...data,
|
|
||||||
},
|
|
||||||
'time_groups',
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
// update
|
|
||||||
else {
|
|
||||||
await this.couchService.updateDoc(
|
|
||||||
{
|
|
||||||
_id: data.id,
|
|
||||||
...data,
|
|
||||||
},
|
|
||||||
'time_groups',
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -5,17 +5,13 @@ import { Public } from 'src/core/guards';
|
||||||
import * as Nano from 'nano';
|
import * as Nano from 'nano';
|
||||||
import { CreateUserPrivilegeDto } from 'src/modules/user-related/user-privilege/infrastructure/dto/create-user-privilege.dto';
|
import { CreateUserPrivilegeDto } from 'src/modules/user-related/user-privilege/infrastructure/dto/create-user-privilege.dto';
|
||||||
import { ConfigService } from '@nestjs/config';
|
import { ConfigService } from '@nestjs/config';
|
||||||
import { CouchService } from '../data/services/couch.service';
|
|
||||||
|
|
||||||
@ApiTags(`couch`)
|
@ApiTags(`couch`)
|
||||||
@Controller('v1/couch')
|
@Controller('v1/couch')
|
||||||
@Public()
|
@Public()
|
||||||
@Injectable()
|
@Injectable()
|
||||||
export class CouchDataController {
|
export class CouchDataController {
|
||||||
constructor(
|
constructor(private configService: ConfigService) {}
|
||||||
private configService: ConfigService,
|
|
||||||
private couchService: CouchService,
|
|
||||||
) {}
|
|
||||||
|
|
||||||
get nanoInstance() {
|
get nanoInstance() {
|
||||||
const couchConfiguration = this.configService.get<string>('COUCHDB_CONFIG');
|
const couchConfiguration = this.configService.get<string>('COUCHDB_CONFIG');
|
||||||
|
@ -68,11 +64,4 @@ export class CouchDataController {
|
||||||
// return people.get();
|
// return people.get();
|
||||||
} catch (error) {}
|
} catch (error) {}
|
||||||
}
|
}
|
||||||
|
|
||||||
@Public(true)
|
|
||||||
@Get('clear-transactions')
|
|
||||||
async clearTransactions(): Promise<string> {
|
|
||||||
await this.couchService.clearTransactions();
|
|
||||||
return 'OK';
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,105 +0,0 @@
|
||||||
import { Module } from '@nestjs/common';
|
|
||||||
import { ConfigModule } from '@nestjs/config';
|
|
||||||
import { TypeOrmModule } from '@nestjs/typeorm';
|
|
||||||
import { CONNECTION_NAME } from 'src/core/strings/constants/base.constants';
|
|
||||||
import { DataSchedulingDataService } from './data/services/data-scheduling-data.service';
|
|
||||||
import { DataSchedulingReadService } from './data/services/data-scheduling-read.service';
|
|
||||||
import {
|
|
||||||
DataSchedulingLogReadController,
|
|
||||||
DataSchedulingReadController,
|
|
||||||
} from './infrastructure/data-scheduling-read.controller';
|
|
||||||
import { DataSchedulingReadOrchestrator } from './domain/usecases/data-scheduling-read.orchestrator';
|
|
||||||
import {
|
|
||||||
DataSchedulingDataController,
|
|
||||||
DataSchedulingDefaultController,
|
|
||||||
DataSchedulingDataLogController,
|
|
||||||
DataSchedulingSetupController,
|
|
||||||
} from './infrastructure/data-scheduling-data.controller';
|
|
||||||
import { DataSchedulingDataOrchestrator } from './domain/usecases/data-scheduling-data.orchestrator';
|
|
||||||
import { CreateDataSchedulingManager } from './domain/usecases/managers/create-data-scheduling.manager';
|
|
||||||
import { CqrsModule } from '@nestjs/cqrs';
|
|
||||||
import { IndexDataSchedulingManager } from './domain/usecases/managers/index-data-scheduling.manager';
|
|
||||||
import { DeleteDataSchedulingManager } from './domain/usecases/managers/delete-data-scheduling.manager';
|
|
||||||
import { UpdateDataSchedulingManager } from './domain/usecases/managers/update-data-scheduling.manager';
|
|
||||||
import { ActiveDataSchedulingManager } from './domain/usecases/managers/active-data-scheduling.manager';
|
|
||||||
import { ConfirmDataSchedulingManager } from './domain/usecases/managers/confirm-data-scheduling.manager';
|
|
||||||
import { InactiveDataSchedulingManager } from './domain/usecases/managers/inactive-data-scheduling.manager';
|
|
||||||
import { DetailDataSchedulingManager } from './domain/usecases/managers/detail-data-scheduling.manager';
|
|
||||||
import { BatchDeleteDataSchedulingManager } from './domain/usecases/managers/batch-delete-data-scheduling.manager';
|
|
||||||
import { BatchActiveDataSchedulingManager } from './domain/usecases/managers/batch-active-data-scheduling.manager';
|
|
||||||
import { BatchConfirmDataSchedulingManager } from './domain/usecases/managers/batch-confirm-data-scheduling.manager';
|
|
||||||
import { BatchInactiveDataSchedulingManager } from './domain/usecases/managers/batch-inactive-data-scheduling.manager';
|
|
||||||
import { DataSchedulingModel } from './data/models/data-scheduling.model';
|
|
||||||
import { DataSchedulingDefaultModel } from './data/models/data-scheduling-default.model';
|
|
||||||
import { DataSchedulingManager } from './domain/usecases/managers/data-scheduling-default.manager';
|
|
||||||
import { SetupSchedulingGuard } from './infrastructure/guards/setup-scheduling.guard';
|
|
||||||
|
|
||||||
import { DataSchedulingChangeStatusHandler } from './domain/usecases/handlers/data-scheduling-change-status.handler';
|
|
||||||
import { DataSchedulingCreatedHandler } from './domain/usecases/handlers/data-scheduling-created.handler';
|
|
||||||
import { DataSchedulingDeletedHandler } from './domain/usecases/handlers/data-scheduling-deleted.handler';
|
|
||||||
import { DataSchedulingUpdatedHandler } from './domain/usecases/handlers/data-scheduling-updated.handler';
|
|
||||||
|
|
||||||
import { JwtModule } from '@nestjs/jwt';
|
|
||||||
import { JWT_EXPIRED } from 'src/core/sessions/constants';
|
|
||||||
import { JWT_SECRET } from 'src/core/sessions/constants';
|
|
||||||
|
|
||||||
import { DataSchedulingLogDataService } from './data/services/data-scheduling-log-data.service';
|
|
||||||
import { DataSchedulingLogModel } from './data/models/data-scheduling-log.model';
|
|
||||||
import { DataSchedulingLogReadService } from './data/services/data-scheduling-log-read.service';
|
|
||||||
import { IndexDataSchedulingLogManager } from './domain/usecases/managers/index-data-scheduling-log.manager';
|
|
||||||
|
|
||||||
@Module({
|
|
||||||
imports: [
|
|
||||||
ConfigModule.forRoot(),
|
|
||||||
TypeOrmModule.forFeature(
|
|
||||||
[DataSchedulingModel, DataSchedulingDefaultModel, DataSchedulingLogModel],
|
|
||||||
CONNECTION_NAME.DEFAULT,
|
|
||||||
),
|
|
||||||
JwtModule.register({
|
|
||||||
secret: JWT_SECRET,
|
|
||||||
signOptions: { expiresIn: JWT_EXPIRED },
|
|
||||||
}),
|
|
||||||
CqrsModule,
|
|
||||||
],
|
|
||||||
controllers: [
|
|
||||||
DataSchedulingDataController,
|
|
||||||
DataSchedulingReadController,
|
|
||||||
DataSchedulingDefaultController,
|
|
||||||
DataSchedulingSetupController,
|
|
||||||
DataSchedulingLogReadController,
|
|
||||||
DataSchedulingDataLogController,
|
|
||||||
],
|
|
||||||
providers: [
|
|
||||||
SetupSchedulingGuard,
|
|
||||||
IndexDataSchedulingManager,
|
|
||||||
DetailDataSchedulingManager,
|
|
||||||
CreateDataSchedulingManager,
|
|
||||||
DeleteDataSchedulingManager,
|
|
||||||
UpdateDataSchedulingManager,
|
|
||||||
ActiveDataSchedulingManager,
|
|
||||||
ConfirmDataSchedulingManager,
|
|
||||||
InactiveDataSchedulingManager,
|
|
||||||
BatchDeleteDataSchedulingManager,
|
|
||||||
BatchActiveDataSchedulingManager,
|
|
||||||
BatchConfirmDataSchedulingManager,
|
|
||||||
BatchInactiveDataSchedulingManager,
|
|
||||||
|
|
||||||
DataSchedulingLogDataService,
|
|
||||||
DataSchedulingLogReadService,
|
|
||||||
DataSchedulingDataService,
|
|
||||||
DataSchedulingReadService,
|
|
||||||
DataSchedulingLogDataService,
|
|
||||||
|
|
||||||
DataSchedulingDataOrchestrator,
|
|
||||||
DataSchedulingReadOrchestrator,
|
|
||||||
|
|
||||||
DataSchedulingManager,
|
|
||||||
IndexDataSchedulingLogManager,
|
|
||||||
|
|
||||||
DataSchedulingChangeStatusHandler,
|
|
||||||
DataSchedulingCreatedHandler,
|
|
||||||
DataSchedulingDeletedHandler,
|
|
||||||
DataSchedulingUpdatedHandler,
|
|
||||||
],
|
|
||||||
})
|
|
||||||
export class DataSchedulingModule {}
|
|
|
@ -1,13 +0,0 @@
|
||||||
import { TABLE_NAME } from 'src/core/strings/constants/table.constants';
|
|
||||||
import { DataSchedulingDefaultEntity } from '../../domain/entities/data-scheduling.entity';
|
|
||||||
import { Column, Entity } from 'typeorm';
|
|
||||||
import { BaseModel } from 'src/core/modules/data/model/base.model';
|
|
||||||
|
|
||||||
@Entity(TABLE_NAME.DATA_SCHEDULING_DEFAULT)
|
|
||||||
export class DataSchedulingDefaultModel
|
|
||||||
extends BaseModel<DataSchedulingDefaultEntity>
|
|
||||||
implements DataSchedulingDefaultEntity
|
|
||||||
{
|
|
||||||
@Column('int', { nullable: false })
|
|
||||||
default_value: number;
|
|
||||||
}
|
|
|
@ -1,44 +0,0 @@
|
||||||
import { TABLE_NAME } from 'src/core/strings/constants/table.constants';
|
|
||||||
import {
|
|
||||||
DataSchedulingLogEntity,
|
|
||||||
SCHEDULING_LOG_ACTION_ENUM,
|
|
||||||
SCHEDULING_LOG_TYPE_ENUM,
|
|
||||||
} from '../../domain/entities/data-scheduling.entity';
|
|
||||||
import { Column, Entity } from 'typeorm';
|
|
||||||
import { BaseStatusModel } from 'src/core/modules/data/model/base-status.model';
|
|
||||||
|
|
||||||
@Entity(TABLE_NAME.DATA_SCHEDULING_LOG)
|
|
||||||
export class DataSchedulingLogModel
|
|
||||||
extends BaseStatusModel<DataSchedulingLogEntity>
|
|
||||||
implements DataSchedulingLogEntity
|
|
||||||
{
|
|
||||||
@Column({ type: 'enum', enum: SCHEDULING_LOG_TYPE_ENUM, nullable: false })
|
|
||||||
type: SCHEDULING_LOG_TYPE_ENUM;
|
|
||||||
|
|
||||||
@Column({ type: 'enum', enum: SCHEDULING_LOG_ACTION_ENUM, nullable: false })
|
|
||||||
action: SCHEDULING_LOG_ACTION_ENUM;
|
|
||||||
|
|
||||||
@Column({ type: 'bigint', nullable: false })
|
|
||||||
log_created_at: number;
|
|
||||||
|
|
||||||
@Column('varchar', { name: 'data_id', nullable: true })
|
|
||||||
data_id: string;
|
|
||||||
|
|
||||||
@Column('varchar', { name: 'name', nullable: true })
|
|
||||||
name: string;
|
|
||||||
|
|
||||||
@Column('varchar', { name: 'indexing_key', nullable: true })
|
|
||||||
indexing_key: string;
|
|
||||||
|
|
||||||
@Column('date', { name: 'schedule_date_from', nullable: true })
|
|
||||||
schedule_date_from: Date;
|
|
||||||
|
|
||||||
@Column('date', { name: 'schedule_date_to', nullable: true })
|
|
||||||
schedule_date_to: Date;
|
|
||||||
|
|
||||||
@Column('int', { nullable: true })
|
|
||||||
default_value: number;
|
|
||||||
|
|
||||||
@Column('text', { name: 'description', nullable: true })
|
|
||||||
description: string;
|
|
||||||
}
|
|
|
@ -1,22 +0,0 @@
|
||||||
import { TABLE_NAME } from 'src/core/strings/constants/table.constants';
|
|
||||||
import { DataSchedulingEntity } from '../../domain/entities/data-scheduling.entity';
|
|
||||||
import { Column, Entity } from 'typeorm';
|
|
||||||
import { BaseStatusModel } from 'src/core/modules/data/model/base-status.model';
|
|
||||||
|
|
||||||
@Entity(TABLE_NAME.DATA_SCHEDULING)
|
|
||||||
export class DataSchedulingModel
|
|
||||||
extends BaseStatusModel<DataSchedulingEntity>
|
|
||||||
implements DataSchedulingEntity
|
|
||||||
{
|
|
||||||
@Column('varchar', { name: 'name' })
|
|
||||||
name: string;
|
|
||||||
|
|
||||||
@Column('varchar', { name: 'indexing_key' })
|
|
||||||
indexing_key: string;
|
|
||||||
|
|
||||||
@Column('date', { name: 'schedule_date_from', nullable: false })
|
|
||||||
schedule_date_from: Date;
|
|
||||||
|
|
||||||
@Column('date', { name: 'schedule_date_to', nullable: false })
|
|
||||||
schedule_date_to: Date;
|
|
||||||
}
|
|
|
@ -1,17 +0,0 @@
|
||||||
import { Injectable } from '@nestjs/common';
|
|
||||||
import { BaseDataService } from 'src/core/modules/data/service/base-data.service';
|
|
||||||
import { DataSchedulingEntity } from '../../domain/entities/data-scheduling.entity';
|
|
||||||
import { InjectRepository } from '@nestjs/typeorm';
|
|
||||||
import { DataSchedulingModel } from '../models/data-scheduling.model';
|
|
||||||
import { CONNECTION_NAME } from 'src/core/strings/constants/base.constants';
|
|
||||||
import { Repository } from 'typeorm';
|
|
||||||
|
|
||||||
@Injectable()
|
|
||||||
export class DataSchedulingDataService extends BaseDataService<DataSchedulingEntity> {
|
|
||||||
constructor(
|
|
||||||
@InjectRepository(DataSchedulingModel, CONNECTION_NAME.DEFAULT)
|
|
||||||
private repo: Repository<DataSchedulingModel>,
|
|
||||||
) {
|
|
||||||
super(repo);
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -1,33 +0,0 @@
|
||||||
import { Injectable } from '@nestjs/common';
|
|
||||||
import { InjectRepository } from '@nestjs/typeorm';
|
|
||||||
import { CONNECTION_NAME } from 'src/core/strings/constants/base.constants';
|
|
||||||
import { DataSchedulingLogModel } from '../models/data-scheduling-log.model';
|
|
||||||
import { Repository } from 'typeorm';
|
|
||||||
import { TABLE_NAME } from 'src/core/strings/constants/table.constants';
|
|
||||||
|
|
||||||
@Injectable()
|
|
||||||
export class DataSchedulingLogDataService {
|
|
||||||
constructor(
|
|
||||||
@InjectRepository(DataSchedulingLogModel, CONNECTION_NAME.DEFAULT)
|
|
||||||
private repo: Repository<DataSchedulingLogModel>,
|
|
||||||
) {}
|
|
||||||
|
|
||||||
async create(entity: any): Promise<any> {
|
|
||||||
return await this.repo.save(entity);
|
|
||||||
}
|
|
||||||
|
|
||||||
async deleteRange(from: number, to: number): Promise<any> {
|
|
||||||
try {
|
|
||||||
const deleteResult = await this.repo
|
|
||||||
.createQueryBuilder()
|
|
||||||
.delete()
|
|
||||||
.from(TABLE_NAME.DATA_SCHEDULING_LOG)
|
|
||||||
.where('log_created_at BETWEEN :from AND :to', { from, to })
|
|
||||||
.execute();
|
|
||||||
|
|
||||||
return deleteResult;
|
|
||||||
} catch (error) {
|
|
||||||
throw new Error('Failed to delete range due to an internal error.');
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -1,17 +0,0 @@
|
||||||
import { Injectable } from '@nestjs/common';
|
|
||||||
import { DataSchedulingLogEntity } from '../../domain/entities/data-scheduling.entity';
|
|
||||||
import { InjectRepository } from '@nestjs/typeorm';
|
|
||||||
import { BaseReadService } from 'src/core/modules/data/service/base-read.service';
|
|
||||||
import { CONNECTION_NAME } from 'src/core/strings/constants/base.constants';
|
|
||||||
import { Repository } from 'typeorm';
|
|
||||||
import { DataSchedulingLogModel } from '../models/data-scheduling-log.model';
|
|
||||||
|
|
||||||
@Injectable()
|
|
||||||
export class DataSchedulingLogReadService extends BaseReadService<DataSchedulingLogEntity> {
|
|
||||||
constructor(
|
|
||||||
@InjectRepository(DataSchedulingLogModel, CONNECTION_NAME.DEFAULT)
|
|
||||||
private repo: Repository<DataSchedulingLogModel>,
|
|
||||||
) {
|
|
||||||
super(repo);
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -1,17 +0,0 @@
|
||||||
import { Injectable } from '@nestjs/common';
|
|
||||||
import { DataSchedulingEntity } from '../../domain/entities/data-scheduling.entity';
|
|
||||||
import { InjectRepository } from '@nestjs/typeorm';
|
|
||||||
import { DataSchedulingModel } from '../models/data-scheduling.model';
|
|
||||||
import { CONNECTION_NAME } from 'src/core/strings/constants/base.constants';
|
|
||||||
import { Repository } from 'typeorm';
|
|
||||||
import { BaseReadService } from 'src/core/modules/data/service/base-read.service';
|
|
||||||
|
|
||||||
@Injectable()
|
|
||||||
export class DataSchedulingReadService extends BaseReadService<DataSchedulingEntity> {
|
|
||||||
constructor(
|
|
||||||
@InjectRepository(DataSchedulingModel, CONNECTION_NAME.DEFAULT)
|
|
||||||
private repo: Repository<DataSchedulingModel>,
|
|
||||||
) {
|
|
||||||
super(repo);
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -1,47 +0,0 @@
|
||||||
import { BaseStatusEntity } from 'src/core/modules/domain/entities/base-status.entity';
|
|
||||||
import { BaseEntity } from 'src/core/modules/domain/entities/base.entity';
|
|
||||||
import { STATUS } from 'src/core/strings/constants/base.constants';
|
|
||||||
|
|
||||||
export interface DataSchedulingEntity extends BaseStatusEntity {
|
|
||||||
name: string;
|
|
||||||
indexing_key: number | string;
|
|
||||||
schedule_date_from: Date;
|
|
||||||
schedule_date_to: Date;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface DataSchedulingDefaultEntity extends BaseEntity {
|
|
||||||
default_value: number;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface DataSchedulingActiveEntity {
|
|
||||||
value: number;
|
|
||||||
}
|
|
||||||
|
|
||||||
export enum SCHEDULING_LOG_TYPE_ENUM {
|
|
||||||
DEFAULT_PERCENTAGE = 'Default Percentage',
|
|
||||||
DATA_SCHEDULING = 'Data Scheduling',
|
|
||||||
}
|
|
||||||
|
|
||||||
export enum SCHEDULING_LOG_ACTION_ENUM {
|
|
||||||
CREATE = 'CREATE',
|
|
||||||
UPDATE = 'UPDATE',
|
|
||||||
DELETE = 'DELETE',
|
|
||||||
CHANGE_STATUS = 'CHANGE_STATUS',
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface DataSchedulingLogEntity extends BaseStatusEntity {
|
|
||||||
type: SCHEDULING_LOG_TYPE_ENUM;
|
|
||||||
action: SCHEDULING_LOG_ACTION_ENUM;
|
|
||||||
log_created_at: number;
|
|
||||||
|
|
||||||
data_id?: string;
|
|
||||||
|
|
||||||
name?: string;
|
|
||||||
indexing_key?: number | string;
|
|
||||||
schedule_date_from?: Date;
|
|
||||||
schedule_date_to?: Date;
|
|
||||||
|
|
||||||
default_value?: number;
|
|
||||||
|
|
||||||
description?: string;
|
|
||||||
}
|
|
|
@ -1,5 +0,0 @@
|
||||||
import { IEvent } from 'src/core/strings/constants/interface.constants';
|
|
||||||
|
|
||||||
export class DataSchedulingChangeStatusEvent {
|
|
||||||
constructor(public readonly data: IEvent) {}
|
|
||||||
}
|
|
|
@ -1,5 +0,0 @@
|
||||||
import { IEvent } from 'src/core/strings/constants/interface.constants';
|
|
||||||
|
|
||||||
export class DataSchedulingCreatedEvent {
|
|
||||||
constructor(public readonly data: IEvent) {}
|
|
||||||
}
|
|
|
@ -1,5 +0,0 @@
|
||||||
import { IEvent } from 'src/core/strings/constants/interface.constants';
|
|
||||||
|
|
||||||
export class DataSchedulingDeletedEvent {
|
|
||||||
constructor(public readonly data: IEvent) {}
|
|
||||||
}
|
|
|
@ -1,5 +0,0 @@
|
||||||
import { IEvent } from 'src/core/strings/constants/interface.constants';
|
|
||||||
|
|
||||||
export class DataSchedulingUpdatedEvent {
|
|
||||||
constructor(public readonly data: IEvent) {}
|
|
||||||
}
|
|
|
@ -1,6 +0,0 @@
|
||||||
import { BaseFilterEntity } from 'src/core/modules/domain/entities/base-filter.entity';
|
|
||||||
|
|
||||||
export interface FilterDataSchedulingEntity extends BaseFilterEntity {
|
|
||||||
schedule_date_from: Date;
|
|
||||||
schedule_date_to: Date;
|
|
||||||
}
|
|
|
@ -1,125 +0,0 @@
|
||||||
import { Injectable } from '@nestjs/common';
|
|
||||||
import { CreateDataSchedulingManager } from './managers/create-data-scheduling.manager';
|
|
||||||
import { DataSchedulingDataService } from '../../data/services/data-scheduling-data.service';
|
|
||||||
import { DataSchedulingEntity } from '../entities/data-scheduling.entity';
|
|
||||||
import { DeleteDataSchedulingManager } from './managers/delete-data-scheduling.manager';
|
|
||||||
import { UpdateDataSchedulingManager } from './managers/update-data-scheduling.manager';
|
|
||||||
import { BaseDataTransactionOrchestrator } from 'src/core/modules/domain/usecase/orchestrators/base-data-transaction.orchestrator';
|
|
||||||
import { ActiveDataSchedulingManager } from './managers/active-data-scheduling.manager';
|
|
||||||
import { InactiveDataSchedulingManager } from './managers/inactive-data-scheduling.manager';
|
|
||||||
import { ConfirmDataSchedulingManager } from './managers/confirm-data-scheduling.manager';
|
|
||||||
import { STATUS } from 'src/core/strings/constants/base.constants';
|
|
||||||
import { BatchResult } from 'src/core/response/domain/ok-response.interface';
|
|
||||||
import { BatchConfirmDataSchedulingManager } from './managers/batch-confirm-data-scheduling.manager';
|
|
||||||
import { BatchInactiveDataSchedulingManager } from './managers/batch-inactive-data-scheduling.manager';
|
|
||||||
import { BatchActiveDataSchedulingManager } from './managers/batch-active-data-scheduling.manager';
|
|
||||||
import { BatchDeleteDataSchedulingManager } from './managers/batch-delete-data-scheduling.manager';
|
|
||||||
import { TABLE_NAME } from 'src/core/strings/constants/table.constants';
|
|
||||||
|
|
||||||
@Injectable()
|
|
||||||
export class DataSchedulingDataOrchestrator extends BaseDataTransactionOrchestrator<DataSchedulingEntity> {
|
|
||||||
constructor(
|
|
||||||
private createManager: CreateDataSchedulingManager,
|
|
||||||
private updateManager: UpdateDataSchedulingManager,
|
|
||||||
private deleteManager: DeleteDataSchedulingManager,
|
|
||||||
private activeManager: ActiveDataSchedulingManager,
|
|
||||||
private confirmManager: ConfirmDataSchedulingManager,
|
|
||||||
private inactiveManager: InactiveDataSchedulingManager,
|
|
||||||
private batchDeleteManager: BatchDeleteDataSchedulingManager,
|
|
||||||
private batchActiveManager: BatchActiveDataSchedulingManager,
|
|
||||||
private batchConfirmManager: BatchConfirmDataSchedulingManager,
|
|
||||||
private batchInactiveManager: BatchInactiveDataSchedulingManager,
|
|
||||||
private serviceData: DataSchedulingDataService,
|
|
||||||
) {
|
|
||||||
super();
|
|
||||||
}
|
|
||||||
|
|
||||||
async create(data): Promise<DataSchedulingEntity> {
|
|
||||||
this.createManager.setData(data);
|
|
||||||
this.createManager.setService(this.serviceData, TABLE_NAME.DATA_SCHEDULING);
|
|
||||||
await this.createManager.execute();
|
|
||||||
await this.createManager.generateConfig();
|
|
||||||
return this.createManager.getResult();
|
|
||||||
}
|
|
||||||
|
|
||||||
async update(dataId, data): Promise<DataSchedulingEntity> {
|
|
||||||
this.updateManager.setData(dataId, data);
|
|
||||||
this.updateManager.setService(this.serviceData, TABLE_NAME.DATA_SCHEDULING);
|
|
||||||
await this.updateManager.execute();
|
|
||||||
return this.updateManager.getResult();
|
|
||||||
}
|
|
||||||
|
|
||||||
async delete(dataId): Promise<string> {
|
|
||||||
this.deleteManager.setData(dataId);
|
|
||||||
this.deleteManager.setService(this.serviceData, TABLE_NAME.DATA_SCHEDULING);
|
|
||||||
await this.deleteManager.execute();
|
|
||||||
return this.deleteManager.getResult();
|
|
||||||
}
|
|
||||||
|
|
||||||
async batchDelete(dataIds: string[]): Promise<BatchResult> {
|
|
||||||
this.batchDeleteManager.setData(dataIds);
|
|
||||||
this.batchDeleteManager.setService(
|
|
||||||
this.serviceData,
|
|
||||||
TABLE_NAME.DATA_SCHEDULING,
|
|
||||||
);
|
|
||||||
await this.batchDeleteManager.execute();
|
|
||||||
return this.batchDeleteManager.getResult();
|
|
||||||
}
|
|
||||||
|
|
||||||
async active(dataId): Promise<string> {
|
|
||||||
this.activeManager.setData(dataId, STATUS.ACTIVE);
|
|
||||||
this.activeManager.setService(this.serviceData, TABLE_NAME.DATA_SCHEDULING);
|
|
||||||
await this.activeManager.execute();
|
|
||||||
return this.activeManager.getResult();
|
|
||||||
}
|
|
||||||
|
|
||||||
async batchActive(dataIds: string[]): Promise<BatchResult> {
|
|
||||||
this.batchActiveManager.setData(dataIds, STATUS.ACTIVE);
|
|
||||||
this.batchActiveManager.setService(
|
|
||||||
this.serviceData,
|
|
||||||
TABLE_NAME.DATA_SCHEDULING,
|
|
||||||
);
|
|
||||||
await this.batchActiveManager.execute();
|
|
||||||
return this.batchActiveManager.getResult();
|
|
||||||
}
|
|
||||||
|
|
||||||
async confirm(dataId): Promise<string> {
|
|
||||||
this.confirmManager.setData(dataId, STATUS.ACTIVE);
|
|
||||||
this.confirmManager.setService(
|
|
||||||
this.serviceData,
|
|
||||||
TABLE_NAME.DATA_SCHEDULING,
|
|
||||||
);
|
|
||||||
await this.confirmManager.execute();
|
|
||||||
return this.confirmManager.getResult();
|
|
||||||
}
|
|
||||||
|
|
||||||
async batchConfirm(dataIds: string[]): Promise<BatchResult> {
|
|
||||||
this.batchConfirmManager.setData(dataIds, STATUS.ACTIVE);
|
|
||||||
this.batchConfirmManager.setService(
|
|
||||||
this.serviceData,
|
|
||||||
TABLE_NAME.DATA_SCHEDULING,
|
|
||||||
);
|
|
||||||
await this.batchConfirmManager.execute();
|
|
||||||
return this.batchConfirmManager.getResult();
|
|
||||||
}
|
|
||||||
|
|
||||||
async inactive(dataId): Promise<string> {
|
|
||||||
this.inactiveManager.setData(dataId, STATUS.INACTIVE);
|
|
||||||
this.inactiveManager.setService(
|
|
||||||
this.serviceData,
|
|
||||||
TABLE_NAME.DATA_SCHEDULING,
|
|
||||||
);
|
|
||||||
await this.inactiveManager.execute();
|
|
||||||
return this.inactiveManager.getResult();
|
|
||||||
}
|
|
||||||
|
|
||||||
async batchInactive(dataIds: string[]): Promise<BatchResult> {
|
|
||||||
this.batchInactiveManager.setData(dataIds, STATUS.INACTIVE);
|
|
||||||
this.batchInactiveManager.setService(
|
|
||||||
this.serviceData,
|
|
||||||
TABLE_NAME.DATA_SCHEDULING,
|
|
||||||
);
|
|
||||||
await this.batchInactiveManager.execute();
|
|
||||||
return this.batchInactiveManager.getResult();
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -1,50 +0,0 @@
|
||||||
import { Injectable } from '@nestjs/common';
|
|
||||||
import { IndexDataSchedulingManager } from './managers/index-data-scheduling.manager';
|
|
||||||
import { DataSchedulingReadService } from '../../data/services/data-scheduling-read.service';
|
|
||||||
import {
|
|
||||||
DataSchedulingEntity,
|
|
||||||
DataSchedulingLogEntity,
|
|
||||||
} from '../entities/data-scheduling.entity';
|
|
||||||
import { PaginationResponse } from 'src/core/response/domain/ok-response.interface';
|
|
||||||
import { BaseReadOrchestrator } from 'src/core/modules/domain/usecase/orchestrators/base-read.orchestrator';
|
|
||||||
import { DetailDataSchedulingManager } from './managers/detail-data-scheduling.manager';
|
|
||||||
import { TABLE_NAME } from 'src/core/strings/constants/table.constants';
|
|
||||||
import { IndexDataSchedulingLogManager } from './managers/index-data-scheduling-log.manager';
|
|
||||||
import { DataSchedulingLogReadService } from '../../data/services/data-scheduling-log-read.service';
|
|
||||||
|
|
||||||
@Injectable()
|
|
||||||
export class DataSchedulingReadOrchestrator extends BaseReadOrchestrator<DataSchedulingEntity> {
|
|
||||||
constructor(
|
|
||||||
private indexManager: IndexDataSchedulingManager,
|
|
||||||
private indexLogManager: IndexDataSchedulingLogManager,
|
|
||||||
private detailManager: DetailDataSchedulingManager,
|
|
||||||
private serviceData: DataSchedulingReadService,
|
|
||||||
private logServiceData: DataSchedulingLogReadService,
|
|
||||||
) {
|
|
||||||
super();
|
|
||||||
}
|
|
||||||
|
|
||||||
async index(params): Promise<PaginationResponse<DataSchedulingEntity>> {
|
|
||||||
this.indexManager.setFilterParam(params);
|
|
||||||
this.indexManager.setService(this.serviceData, TABLE_NAME.DATA_SCHEDULING);
|
|
||||||
await this.indexManager.execute();
|
|
||||||
return this.indexManager.getResult();
|
|
||||||
}
|
|
||||||
|
|
||||||
async indexLog(params): Promise<PaginationResponse<DataSchedulingLogEntity>> {
|
|
||||||
this.indexLogManager.setFilterParam(params);
|
|
||||||
this.indexLogManager.setService(
|
|
||||||
this.logServiceData,
|
|
||||||
TABLE_NAME.DATA_SCHEDULING_LOG,
|
|
||||||
);
|
|
||||||
await this.indexLogManager.execute();
|
|
||||||
return this.indexLogManager.getResult();
|
|
||||||
}
|
|
||||||
|
|
||||||
async detail(dataId: string): Promise<DataSchedulingEntity> {
|
|
||||||
this.detailManager.setData(dataId);
|
|
||||||
this.detailManager.setService(this.serviceData, TABLE_NAME.DATA_SCHEDULING);
|
|
||||||
await this.detailManager.execute();
|
|
||||||
return this.detailManager.getResult();
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -1,63 +0,0 @@
|
||||||
import { EventsHandler, IEventHandler } from '@nestjs/cqrs';
|
|
||||||
import { DataSchedulingChangeStatusEvent } from '../../entities/event/data-scheduling-change-status.event';
|
|
||||||
import { capitalizeEachWord } from 'src/modules/reports/shared/helpers';
|
|
||||||
import {
|
|
||||||
DataSchedulingLogEntity,
|
|
||||||
SCHEDULING_LOG_ACTION_ENUM,
|
|
||||||
SCHEDULING_LOG_TYPE_ENUM,
|
|
||||||
} from '../../entities/data-scheduling.entity';
|
|
||||||
import { Logger } from '@nestjs/common';
|
|
||||||
import { DataSchedulingLogDataService } from '../../../data/services/data-scheduling-log-data.service';
|
|
||||||
import { decryptionTotal } from '../../../infrastructure/helpers';
|
|
||||||
|
|
||||||
@EventsHandler(DataSchedulingChangeStatusEvent)
|
|
||||||
export class DataSchedulingChangeStatusHandler
|
|
||||||
implements IEventHandler<DataSchedulingChangeStatusEvent>
|
|
||||||
{
|
|
||||||
private readonly logger = new Logger(DataSchedulingChangeStatusHandler.name);
|
|
||||||
|
|
||||||
constructor(private service: DataSchedulingLogDataService) {}
|
|
||||||
|
|
||||||
async handle(event: DataSchedulingChangeStatusEvent) {
|
|
||||||
// Prevent execution if the event data is null, which can happen if triggered from the default percentage update service.
|
|
||||||
if (event.data?.data) {
|
|
||||||
const oldData = event?.data?.old;
|
|
||||||
const newData = event?.data?.data;
|
|
||||||
|
|
||||||
const oldStatus = capitalizeEachWord(oldData?.status);
|
|
||||||
const newStatus = capitalizeEachWord(newData?.status);
|
|
||||||
|
|
||||||
const scheduleName = newData?.name || 'an item';
|
|
||||||
const editorName = newData.editor_name || 'System';
|
|
||||||
const totalPercentage = decryptionTotal(newData?.indexing_key);
|
|
||||||
|
|
||||||
const description = `<div><b>${editorName}</b> changed the status of <b><i>${scheduleName} (${totalPercentage}%)</i></b> schedule from <b><i>${newData?.schedule_date_from}</i></b> to <b><i>${newData.schedule_date_to}</i></b> from <b><i>${oldStatus}</i></b> to <b><i>${newStatus}</i></b>.</div>`;
|
|
||||||
|
|
||||||
const payload: DataSchedulingLogEntity = {
|
|
||||||
type: SCHEDULING_LOG_TYPE_ENUM.DATA_SCHEDULING,
|
|
||||||
action: SCHEDULING_LOG_ACTION_ENUM.CHANGE_STATUS,
|
|
||||||
log_created_at: new Date().getTime(),
|
|
||||||
|
|
||||||
data_id: newData?.id,
|
|
||||||
name: newData?.name,
|
|
||||||
indexing_key: newData?.indexing_key,
|
|
||||||
schedule_date_from: newData?.schedule_date_from,
|
|
||||||
schedule_date_to: newData?.schedule_date_to,
|
|
||||||
|
|
||||||
status: newData?.status,
|
|
||||||
creator_id: newData?.creator_id,
|
|
||||||
creator_name: newData?.creator_name,
|
|
||||||
editor_id: newData?.editor_id,
|
|
||||||
editor_name: newData?.editor_name,
|
|
||||||
created_at: newData?.created_at,
|
|
||||||
updated_at: newData?.updated_at,
|
|
||||||
description: description,
|
|
||||||
};
|
|
||||||
|
|
||||||
await this.service.create(payload as any);
|
|
||||||
this.logger.verbose(
|
|
||||||
`[SCHEDULING LOG] Change status data for ID: ${payload.data_id}`,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -1,53 +0,0 @@
|
||||||
import { EventsHandler, IEventHandler } from '@nestjs/cqrs';
|
|
||||||
import { DataSchedulingCreatedEvent } from '../../entities/event/data-scheduling-created.event';
|
|
||||||
import {
|
|
||||||
DataSchedulingLogEntity,
|
|
||||||
SCHEDULING_LOG_ACTION_ENUM,
|
|
||||||
SCHEDULING_LOG_TYPE_ENUM,
|
|
||||||
} from '../../entities/data-scheduling.entity';
|
|
||||||
import { decryptionTotal } from '../../../infrastructure/helpers';
|
|
||||||
import { Logger } from '@nestjs/common';
|
|
||||||
import { DataSchedulingLogDataService } from '../../../data/services/data-scheduling-log-data.service';
|
|
||||||
|
|
||||||
@EventsHandler(DataSchedulingCreatedEvent)
|
|
||||||
export class DataSchedulingCreatedHandler
|
|
||||||
implements IEventHandler<DataSchedulingCreatedEvent>
|
|
||||||
{
|
|
||||||
private readonly logger = new Logger(DataSchedulingCreatedHandler.name);
|
|
||||||
|
|
||||||
constructor(private service: DataSchedulingLogDataService) {}
|
|
||||||
|
|
||||||
async handle(event: DataSchedulingCreatedEvent) {
|
|
||||||
const data = event?.data?.data;
|
|
||||||
const totalPercentage = decryptionTotal(data?.indexing_key);
|
|
||||||
|
|
||||||
const scheduleName = data?.name || 'a new schedule';
|
|
||||||
const description = `<div><b>${data.creator_name}</b> created <b><i>${scheduleName}</i></b> schedule from <b><i>${data?.schedule_date_from}</i></b> to <b><i>${data.schedule_date_to}</i></b> with a total percentage of <b><i>${totalPercentage}%</i></b>.</div>`;
|
|
||||||
|
|
||||||
const payload: DataSchedulingLogEntity = {
|
|
||||||
type: SCHEDULING_LOG_TYPE_ENUM.DATA_SCHEDULING,
|
|
||||||
action: SCHEDULING_LOG_ACTION_ENUM.CREATE,
|
|
||||||
log_created_at: new Date().getTime(),
|
|
||||||
|
|
||||||
data_id: data?.id,
|
|
||||||
name: data?.name,
|
|
||||||
indexing_key: data?.indexing_key,
|
|
||||||
schedule_date_from: data?.schedule_date_from,
|
|
||||||
schedule_date_to: data?.schedule_date_to,
|
|
||||||
|
|
||||||
status: data?.status,
|
|
||||||
creator_id: data?.creator_id,
|
|
||||||
creator_name: data?.creator_name,
|
|
||||||
editor_id: data?.editor_id,
|
|
||||||
editor_name: data?.editor_name,
|
|
||||||
created_at: data?.created_at,
|
|
||||||
updated_at: data?.updated_at,
|
|
||||||
description: description,
|
|
||||||
};
|
|
||||||
|
|
||||||
await this.service.create(payload as any);
|
|
||||||
this.logger.verbose(
|
|
||||||
`[SCHEDULING LOG] Create data for ID: ${payload.data_id}`,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -1,60 +0,0 @@
|
||||||
import { EventsHandler, IEventHandler } from '@nestjs/cqrs';
|
|
||||||
import { DataSchedulingDeletedEvent } from '../../entities/event/data-scheduling-deleted.event';
|
|
||||||
import {
|
|
||||||
DataSchedulingLogEntity,
|
|
||||||
SCHEDULING_LOG_ACTION_ENUM,
|
|
||||||
SCHEDULING_LOG_TYPE_ENUM,
|
|
||||||
} from '../../entities/data-scheduling.entity';
|
|
||||||
import { Logger } from '@nestjs/common';
|
|
||||||
import { DataSchedulingLogDataService } from '../../../data/services/data-scheduling-log-data.service';
|
|
||||||
import { decryptionTotal } from '../../../infrastructure/helpers';
|
|
||||||
|
|
||||||
@EventsHandler(DataSchedulingDeletedEvent)
|
|
||||||
export class DataSchedulingDeletedHandler
|
|
||||||
implements IEventHandler<DataSchedulingDeletedEvent>
|
|
||||||
{
|
|
||||||
private readonly logger = new Logger(DataSchedulingDeletedHandler.name);
|
|
||||||
|
|
||||||
constructor(private service: DataSchedulingLogDataService) {}
|
|
||||||
|
|
||||||
async handle(event: DataSchedulingDeletedEvent) {
|
|
||||||
const deletedData = event?.data?.data;
|
|
||||||
const user = event?.data?.user;
|
|
||||||
|
|
||||||
const deleterName =
|
|
||||||
user?.name ||
|
|
||||||
deletedData?.editor_name ||
|
|
||||||
deletedData?.creator_name ||
|
|
||||||
'System';
|
|
||||||
|
|
||||||
const scheduleName = deletedData?.name || 'an item';
|
|
||||||
const totalPercentage = decryptionTotal(deletedData?.indexing_key);
|
|
||||||
const description = `<div><b>${deleterName}</b> deleted schedule: <b><i>${scheduleName} (${totalPercentage}%)</i></b> schedule from <b><i>${deletedData?.schedule_date_from}</i></b> to <b><i>${deletedData.schedule_date_to}</i></b>.</div>`;
|
|
||||||
|
|
||||||
const payload: DataSchedulingLogEntity = {
|
|
||||||
type: SCHEDULING_LOG_TYPE_ENUM.DATA_SCHEDULING,
|
|
||||||
action: SCHEDULING_LOG_ACTION_ENUM.DELETE,
|
|
||||||
log_created_at: new Date().getTime(),
|
|
||||||
|
|
||||||
data_id: deletedData?.id,
|
|
||||||
name: deletedData?.name,
|
|
||||||
indexing_key: deletedData?.indexing_key,
|
|
||||||
schedule_date_from: deletedData?.schedule_date_from,
|
|
||||||
schedule_date_to: deletedData?.schedule_date_to,
|
|
||||||
status: deletedData?.status,
|
|
||||||
|
|
||||||
creator_id: deletedData?.creator_id,
|
|
||||||
creator_name: deletedData?.creator_name,
|
|
||||||
editor_id: deletedData?.editor_id,
|
|
||||||
editor_name: deletedData?.editor_name,
|
|
||||||
created_at: deletedData?.created_at,
|
|
||||||
updated_at: deletedData?.updated_at,
|
|
||||||
description: description,
|
|
||||||
};
|
|
||||||
|
|
||||||
await this.service.create(payload as any);
|
|
||||||
this.logger.verbose(
|
|
||||||
`[SCHEDULING LOG] Delete data for ID: ${payload.data_id}`,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -1,157 +0,0 @@
|
||||||
import { EventsHandler, IEventHandler } from '@nestjs/cqrs';
|
|
||||||
import { DataSchedulingUpdatedEvent } from '../../entities/event/data-scheduling-updated.event';
|
|
||||||
import {
|
|
||||||
DataSchedulingLogEntity,
|
|
||||||
SCHEDULING_LOG_ACTION_ENUM,
|
|
||||||
SCHEDULING_LOG_TYPE_ENUM,
|
|
||||||
} from '../../entities/data-scheduling.entity';
|
|
||||||
import {
|
|
||||||
decryptionTotal,
|
|
||||||
encryptionTotal,
|
|
||||||
} from '../../../infrastructure/helpers';
|
|
||||||
import { Logger } from '@nestjs/common';
|
|
||||||
import { DataSchedulingLogDataService } from '../../../data/services/data-scheduling-log-data.service';
|
|
||||||
|
|
||||||
@EventsHandler(DataSchedulingUpdatedEvent)
|
|
||||||
export class DataSchedulingUpdatedHandler
|
|
||||||
implements IEventHandler<DataSchedulingUpdatedEvent>
|
|
||||||
{
|
|
||||||
private readonly logger = new Logger(DataSchedulingUpdatedHandler.name);
|
|
||||||
|
|
||||||
constructor(private service: DataSchedulingLogDataService) {}
|
|
||||||
|
|
||||||
// Map for readable labels
|
|
||||||
private readonly labelMap: { [key: string]: string } = {
|
|
||||||
name: 'Name',
|
|
||||||
indexing_key: 'Total Data',
|
|
||||||
schedule_date_from: 'Start Date',
|
|
||||||
schedule_date_to: 'End Date',
|
|
||||||
};
|
|
||||||
|
|
||||||
// Relevant keys for comparing changes
|
|
||||||
private readonly keysToCompare: string[] = [
|
|
||||||
'name',
|
|
||||||
'indexing_key',
|
|
||||||
'schedule_date_from',
|
|
||||||
'schedule_date_to',
|
|
||||||
];
|
|
||||||
|
|
||||||
async handle(event: DataSchedulingUpdatedEvent) {
|
|
||||||
const oldData = event?.data?.old;
|
|
||||||
// Decrypt oldData.indexing_key here before comparison
|
|
||||||
if (oldData?.indexing_key !== undefined && oldData?.indexing_key !== null) {
|
|
||||||
oldData.indexing_key = decryptionTotal(oldData.indexing_key);
|
|
||||||
}
|
|
||||||
|
|
||||||
const newData = event?.data?.data;
|
|
||||||
// Decrypt newData.indexing_key here before comparison
|
|
||||||
if (newData?.indexing_key !== undefined && newData?.indexing_key !== null) {
|
|
||||||
newData.indexing_key = decryptionTotal(newData.indexing_key);
|
|
||||||
}
|
|
||||||
|
|
||||||
const changingData = this.getChangingData(oldData, newData);
|
|
||||||
const description = this.generateDescription(
|
|
||||||
oldData,
|
|
||||||
newData,
|
|
||||||
changingData,
|
|
||||||
);
|
|
||||||
|
|
||||||
const payload: DataSchedulingLogEntity = {
|
|
||||||
type: SCHEDULING_LOG_TYPE_ENUM.DATA_SCHEDULING,
|
|
||||||
action: SCHEDULING_LOG_ACTION_ENUM.UPDATE,
|
|
||||||
log_created_at: new Date().getTime(),
|
|
||||||
|
|
||||||
data_id: newData?.id,
|
|
||||||
name: newData?.name,
|
|
||||||
indexing_key: encryptionTotal(newData?.indexing_key),
|
|
||||||
schedule_date_from: newData?.schedule_date_from,
|
|
||||||
schedule_date_to: newData?.schedule_date_to,
|
|
||||||
|
|
||||||
status: newData?.status,
|
|
||||||
creator_id: newData?.creator_id,
|
|
||||||
creator_name: newData?.creator_name,
|
|
||||||
editor_id: newData?.editor_id,
|
|
||||||
editor_name: newData?.editor_name,
|
|
||||||
created_at: newData?.created_at,
|
|
||||||
updated_at: newData?.updated_at,
|
|
||||||
description: description,
|
|
||||||
};
|
|
||||||
|
|
||||||
await this.service.create(payload as any);
|
|
||||||
this.logger.verbose(
|
|
||||||
`[SCHEDULING LOG] Update data for ID: ${payload.data_id}`,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Compares old and new data to find changes.
|
|
||||||
* @param oldData Data before the change.
|
|
||||||
* @param newData Data after the change.
|
|
||||||
* @returns An object containing the old and new changed data.
|
|
||||||
*/
|
|
||||||
private getChangingData(oldData: any, newData: any): { old: any; new: any } {
|
|
||||||
const changingData: { old: any; new: any } = { old: {}, new: {} };
|
|
||||||
|
|
||||||
this.keysToCompare.forEach((key) => {
|
|
||||||
// Ensure comparisons are made on decrypted values if decryption happens before this
|
|
||||||
if (oldData?.[key] !== newData?.[key]) {
|
|
||||||
changingData.old[key] = oldData?.[key];
|
|
||||||
changingData.new[key] = newData?.[key];
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
return changingData;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Generates an HTML description string based on data changes.
|
|
||||||
* Includes the name from oldData for identification.
|
|
||||||
* @param oldData Old data, used to get the name of the item.
|
|
||||||
* @param newData New data containing editor information.
|
|
||||||
* @param changingData An object containing the changed data.
|
|
||||||
* @returns The HTML string of the change description.
|
|
||||||
*/
|
|
||||||
private generateDescription(
|
|
||||||
oldData: any,
|
|
||||||
newData: any,
|
|
||||||
changingData: { old: any; new: any },
|
|
||||||
): string {
|
|
||||||
const editorName = newData.editor_name || 'System';
|
|
||||||
const itemName = oldData?.name || 'an item';
|
|
||||||
|
|
||||||
const totalPercentageOld = oldData?.indexing_key;
|
|
||||||
const totalPercentageNew = newData?.indexing_key;
|
|
||||||
const isTotalSame = totalPercentageOld === totalPercentageNew;
|
|
||||||
const labelName = `${
|
|
||||||
isTotalSame
|
|
||||||
? `${totalPercentageNew}%`
|
|
||||||
: `${totalPercentageOld}% to ${totalPercentageNew}%`
|
|
||||||
}`;
|
|
||||||
|
|
||||||
let description = `<div><b>${editorName}</b> has updated schedule for <b><i>${itemName} (${labelName})</i></b> schedule from <b><i>${newData?.schedule_date_from}</i></b> to <b><i>${newData.schedule_date_to}</i></b>.<br>`;
|
|
||||||
|
|
||||||
if (Object.keys(changingData.old).length > 0) {
|
|
||||||
description += `Change details:<ul>`;
|
|
||||||
for (const key in changingData.old) {
|
|
||||||
if (Object.prototype.hasOwnProperty.call(changingData.old, key)) {
|
|
||||||
const label = this.labelMap[key] || key;
|
|
||||||
let oldValue = changingData.old[key] || 'empty';
|
|
||||||
let newValue = changingData.new[key] || 'empty';
|
|
||||||
|
|
||||||
// Add '%' suffix if the key is 'indexing_key'
|
|
||||||
if (key === 'indexing_key') {
|
|
||||||
oldValue = `${oldValue}%`;
|
|
||||||
newValue = `${newValue}%`;
|
|
||||||
}
|
|
||||||
|
|
||||||
description += `<li><b>${label}</b> changed from <b><i>${oldValue}</i></b> to <b><i>${newValue}</i></b>.</li>`;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
description += `</ul></div>`;
|
|
||||||
} else {
|
|
||||||
description += ` No significant data detail changes.</p>`;
|
|
||||||
}
|
|
||||||
|
|
||||||
return description;
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -1,45 +0,0 @@
|
||||||
import { Injectable } from '@nestjs/common';
|
|
||||||
import { BaseUpdateStatusManager } from 'src/core/modules/domain/usecase/managers/base-update-status.manager';
|
|
||||||
import { DataSchedulingEntity } from '../../entities/data-scheduling.entity';
|
|
||||||
import {
|
|
||||||
EventTopics,
|
|
||||||
validateRelations,
|
|
||||||
} from 'src/core/strings/constants/interface.constants';
|
|
||||||
import { DataSchedulingModel } from '../../../data/models/data-scheduling.model';
|
|
||||||
import { DataSchedulingChangeStatusEvent } from '../../entities/event/data-scheduling-change-status.event';
|
|
||||||
|
|
||||||
@Injectable()
|
|
||||||
export class ActiveDataSchedulingManager extends BaseUpdateStatusManager<DataSchedulingEntity> {
|
|
||||||
getResult(): string {
|
|
||||||
return `Success active data ${this.result.name}`;
|
|
||||||
}
|
|
||||||
|
|
||||||
async validateProcess(): Promise<void> {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
async beforeProcess(): Promise<void> {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
async afterProcess(): Promise<void> {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
get validateRelations(): validateRelations[] {
|
|
||||||
return [];
|
|
||||||
}
|
|
||||||
|
|
||||||
get entityTarget(): any {
|
|
||||||
return DataSchedulingModel;
|
|
||||||
}
|
|
||||||
|
|
||||||
get eventTopics(): EventTopics[] {
|
|
||||||
return [
|
|
||||||
{
|
|
||||||
topic: DataSchedulingChangeStatusEvent,
|
|
||||||
data: this.data,
|
|
||||||
},
|
|
||||||
];
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -1,45 +0,0 @@
|
||||||
import { BaseBatchUpdateStatusManager } from 'src/core/modules/domain/usecase/managers/base-batch-update-status.manager';
|
|
||||||
import { DataSchedulingEntity } from '../../entities/data-scheduling.entity';
|
|
||||||
import {
|
|
||||||
EventTopics,
|
|
||||||
validateRelations,
|
|
||||||
} from 'src/core/strings/constants/interface.constants';
|
|
||||||
import { DataSchedulingModel } from '../../../data/models/data-scheduling.model';
|
|
||||||
import { DataSchedulingChangeStatusEvent } from '../../entities/event/data-scheduling-change-status.event';
|
|
||||||
import { BatchResult } from 'src/core/response/domain/ok-response.interface';
|
|
||||||
import { Injectable } from '@nestjs/common';
|
|
||||||
|
|
||||||
@Injectable()
|
|
||||||
export class BatchActiveDataSchedulingManager extends BaseBatchUpdateStatusManager<DataSchedulingEntity> {
|
|
||||||
validateData(data: DataSchedulingEntity): Promise<void> {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
beforeProcess(): Promise<void> {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
afterProcess(): Promise<void> {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
get validateRelations(): validateRelations[] {
|
|
||||||
return [];
|
|
||||||
}
|
|
||||||
|
|
||||||
get entityTarget(): any {
|
|
||||||
return DataSchedulingModel;
|
|
||||||
}
|
|
||||||
|
|
||||||
get eventTopics(): EventTopics[] {
|
|
||||||
return [
|
|
||||||
{
|
|
||||||
topic: DataSchedulingChangeStatusEvent,
|
|
||||||
},
|
|
||||||
];
|
|
||||||
}
|
|
||||||
|
|
||||||
getResult(): BatchResult {
|
|
||||||
return this.result;
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -1,45 +0,0 @@
|
||||||
import { BaseBatchUpdateStatusManager } from 'src/core/modules/domain/usecase/managers/base-batch-update-status.manager';
|
|
||||||
import { DataSchedulingEntity } from '../../entities/data-scheduling.entity';
|
|
||||||
import {
|
|
||||||
EventTopics,
|
|
||||||
validateRelations,
|
|
||||||
} from 'src/core/strings/constants/interface.constants';
|
|
||||||
import { DataSchedulingModel } from '../../../data/models/data-scheduling.model';
|
|
||||||
import { DataSchedulingChangeStatusEvent } from '../../entities/event/data-scheduling-change-status.event';
|
|
||||||
import { BatchResult } from 'src/core/response/domain/ok-response.interface';
|
|
||||||
import { Injectable } from '@nestjs/common';
|
|
||||||
|
|
||||||
@Injectable()
|
|
||||||
export class BatchConfirmDataSchedulingManager extends BaseBatchUpdateStatusManager<DataSchedulingEntity> {
|
|
||||||
validateData(data: DataSchedulingEntity): Promise<void> {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
beforeProcess(): Promise<void> {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
afterProcess(): Promise<void> {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
get validateRelations(): validateRelations[] {
|
|
||||||
return [];
|
|
||||||
}
|
|
||||||
|
|
||||||
get entityTarget(): any {
|
|
||||||
return DataSchedulingModel;
|
|
||||||
}
|
|
||||||
|
|
||||||
get eventTopics(): EventTopics[] {
|
|
||||||
return [
|
|
||||||
{
|
|
||||||
topic: DataSchedulingChangeStatusEvent,
|
|
||||||
},
|
|
||||||
];
|
|
||||||
}
|
|
||||||
|
|
||||||
getResult(): BatchResult {
|
|
||||||
return this.result;
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -1,45 +0,0 @@
|
||||||
import { BaseBatchDeleteManager } from 'src/core/modules/domain/usecase/managers/base-batch-delete.manager';
|
|
||||||
import { DataSchedulingEntity } from '../../entities/data-scheduling.entity';
|
|
||||||
import {
|
|
||||||
EventTopics,
|
|
||||||
validateRelations,
|
|
||||||
} from 'src/core/strings/constants/interface.constants';
|
|
||||||
import { DataSchedulingModel } from '../../../data/models/data-scheduling.model';
|
|
||||||
import { DataSchedulingDeletedEvent } from '../../entities/event/data-scheduling-deleted.event';
|
|
||||||
import { BatchResult } from 'src/core/response/domain/ok-response.interface';
|
|
||||||
import { Injectable } from '@nestjs/common';
|
|
||||||
|
|
||||||
@Injectable()
|
|
||||||
export class BatchDeleteDataSchedulingManager extends BaseBatchDeleteManager<DataSchedulingEntity> {
|
|
||||||
async beforeProcess(): Promise<void> {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
async validateData(data: DataSchedulingEntity): Promise<void> {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
async afterProcess(): Promise<void> {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
get validateRelations(): validateRelations[] {
|
|
||||||
return [];
|
|
||||||
}
|
|
||||||
|
|
||||||
get entityTarget(): any {
|
|
||||||
return DataSchedulingModel;
|
|
||||||
}
|
|
||||||
|
|
||||||
get eventTopics(): EventTopics[] {
|
|
||||||
return [
|
|
||||||
{
|
|
||||||
topic: DataSchedulingDeletedEvent,
|
|
||||||
},
|
|
||||||
];
|
|
||||||
}
|
|
||||||
|
|
||||||
getResult(): BatchResult {
|
|
||||||
return this.result;
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -1,45 +0,0 @@
|
||||||
import { BaseBatchUpdateStatusManager } from 'src/core/modules/domain/usecase/managers/base-batch-update-status.manager';
|
|
||||||
import { DataSchedulingEntity } from '../../entities/data-scheduling.entity';
|
|
||||||
import {
|
|
||||||
EventTopics,
|
|
||||||
validateRelations,
|
|
||||||
} from 'src/core/strings/constants/interface.constants';
|
|
||||||
import { DataSchedulingModel } from '../../../data/models/data-scheduling.model';
|
|
||||||
import { DataSchedulingChangeStatusEvent } from '../../entities/event/data-scheduling-change-status.event';
|
|
||||||
import { BatchResult } from 'src/core/response/domain/ok-response.interface';
|
|
||||||
import { Injectable } from '@nestjs/common';
|
|
||||||
|
|
||||||
@Injectable()
|
|
||||||
export class BatchInactiveDataSchedulingManager extends BaseBatchUpdateStatusManager<DataSchedulingEntity> {
|
|
||||||
validateData(data: DataSchedulingEntity): Promise<void> {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
beforeProcess(): Promise<void> {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
afterProcess(): Promise<void> {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
get validateRelations(): validateRelations[] {
|
|
||||||
return [];
|
|
||||||
}
|
|
||||||
|
|
||||||
get entityTarget(): any {
|
|
||||||
return DataSchedulingModel;
|
|
||||||
}
|
|
||||||
|
|
||||||
get eventTopics(): EventTopics[] {
|
|
||||||
return [
|
|
||||||
{
|
|
||||||
topic: DataSchedulingChangeStatusEvent,
|
|
||||||
},
|
|
||||||
];
|
|
||||||
}
|
|
||||||
|
|
||||||
getResult(): BatchResult {
|
|
||||||
return this.result;
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -1,45 +0,0 @@
|
||||||
import { Injectable } from '@nestjs/common';
|
|
||||||
import { BaseUpdateStatusManager } from 'src/core/modules/domain/usecase/managers/base-update-status.manager';
|
|
||||||
import { DataSchedulingEntity } from '../../entities/data-scheduling.entity';
|
|
||||||
import {
|
|
||||||
EventTopics,
|
|
||||||
validateRelations,
|
|
||||||
} from 'src/core/strings/constants/interface.constants';
|
|
||||||
import { DataSchedulingModel } from '../../../data/models/data-scheduling.model';
|
|
||||||
import { DataSchedulingChangeStatusEvent } from '../../entities/event/data-scheduling-change-status.event';
|
|
||||||
|
|
||||||
@Injectable()
|
|
||||||
export class ConfirmDataSchedulingManager extends BaseUpdateStatusManager<DataSchedulingEntity> {
|
|
||||||
getResult(): string {
|
|
||||||
return `Success active data ${this.result.name}`;
|
|
||||||
}
|
|
||||||
|
|
||||||
async validateProcess(): Promise<void> {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
async beforeProcess(): Promise<void> {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
async afterProcess(): Promise<void> {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
get validateRelations(): validateRelations[] {
|
|
||||||
return [];
|
|
||||||
}
|
|
||||||
|
|
||||||
get entityTarget(): any {
|
|
||||||
return DataSchedulingModel;
|
|
||||||
}
|
|
||||||
|
|
||||||
get eventTopics(): EventTopics[] {
|
|
||||||
return [
|
|
||||||
{
|
|
||||||
topic: DataSchedulingChangeStatusEvent,
|
|
||||||
data: this.data,
|
|
||||||
},
|
|
||||||
];
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -1,88 +0,0 @@
|
||||||
import { Injectable } from '@nestjs/common';
|
|
||||||
import {
|
|
||||||
EventTopics,
|
|
||||||
columnUniques,
|
|
||||||
validateRelations,
|
|
||||||
} from 'src/core/strings/constants/interface.constants';
|
|
||||||
import { DataSchedulingEntity } from '../../entities/data-scheduling.entity';
|
|
||||||
import { DataSchedulingModel } from '../../../data/models/data-scheduling.model';
|
|
||||||
import { BaseCreateManager } from 'src/core/modules/domain/usecase/managers/base-create.manager';
|
|
||||||
import { DataSchedulingCreatedEvent } from '../../entities/event/data-scheduling-created.event';
|
|
||||||
import { encryptionTotal } from '../../../infrastructure/helpers';
|
|
||||||
import * as moment from 'moment';
|
|
||||||
import { STATUS } from 'src/core/strings/constants/base.constants';
|
|
||||||
|
|
||||||
@Injectable()
|
|
||||||
export class CreateDataSchedulingManager extends BaseCreateManager<DataSchedulingEntity> {
|
|
||||||
async beforeProcess(): Promise<void> {
|
|
||||||
const total = this.data.indexing_key;
|
|
||||||
|
|
||||||
if (total > 100) {
|
|
||||||
throw new Error('Maksimal nilai total adalah 100.');
|
|
||||||
}
|
|
||||||
|
|
||||||
const queryBuilder = this.dataService
|
|
||||||
.getRepository()
|
|
||||||
.createQueryBuilder(this.tableName);
|
|
||||||
|
|
||||||
const overlapping = await queryBuilder
|
|
||||||
.where(`${this.tableName}.schedule_date_from <= :schedule_date_to`, {
|
|
||||||
schedule_date_to: this.data.schedule_date_to,
|
|
||||||
})
|
|
||||||
.andWhere(`${this.tableName}.schedule_date_to >= :schedule_date_from`, {
|
|
||||||
schedule_date_from: this.data.schedule_date_from,
|
|
||||||
})
|
|
||||||
.getOne();
|
|
||||||
|
|
||||||
if (this.data) {
|
|
||||||
Object.assign(this.data, {
|
|
||||||
indexing_key: encryptionTotal(total),
|
|
||||||
status: STATUS.ACTIVE,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
// Validation date
|
|
||||||
if (overlapping) {
|
|
||||||
throw new Error('Tanggal yang dimasukkan beririsan dengan data lain.');
|
|
||||||
} else if (this.data.schedule_date_from && this.data.schedule_date_to) {
|
|
||||||
const start_time = moment(this.data.schedule_date_from);
|
|
||||||
const end_time = moment(this.data.schedule_date_to);
|
|
||||||
|
|
||||||
if (end_time.isBefore(start_time)) {
|
|
||||||
throw new Error('Tanggal akhir harus lebih besar dari tanggal mulai.');
|
|
||||||
}
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
async afterProcess(): Promise<void> {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
async generateConfig(): Promise<void> {
|
|
||||||
// TODO: Implement logic here
|
|
||||||
}
|
|
||||||
|
|
||||||
get validateRelations(): validateRelations[] {
|
|
||||||
return [];
|
|
||||||
}
|
|
||||||
|
|
||||||
get uniqueColumns(): columnUniques[] {
|
|
||||||
return [{ column: 'name' }];
|
|
||||||
}
|
|
||||||
|
|
||||||
get eventTopics(): EventTopics[] {
|
|
||||||
return [
|
|
||||||
{
|
|
||||||
topic: DataSchedulingCreatedEvent,
|
|
||||||
data: this.data,
|
|
||||||
},
|
|
||||||
];
|
|
||||||
}
|
|
||||||
|
|
||||||
get entityTarget(): any {
|
|
||||||
return DataSchedulingModel;
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -1,119 +0,0 @@
|
||||||
import { Inject, Injectable } from '@nestjs/common';
|
|
||||||
import { UserProvider, UsersSession } from 'src/core/sessions';
|
|
||||||
import { BLANK_USER } from 'src/core/strings/constants/base.constants';
|
|
||||||
import { EditDataSchedulingDefaultDto } from '../../../infrastructure/dto/data-scheduling.dto';
|
|
||||||
import {
|
|
||||||
DataSchedulingDefaultEntity,
|
|
||||||
DataSchedulingLogEntity,
|
|
||||||
SCHEDULING_LOG_ACTION_ENUM,
|
|
||||||
SCHEDULING_LOG_TYPE_ENUM,
|
|
||||||
} from '../../entities/data-scheduling.entity';
|
|
||||||
import { InjectRepository } from '@nestjs/typeorm';
|
|
||||||
import { DataSchedulingDefaultModel } from '../../../data/models/data-scheduling-default.model';
|
|
||||||
import { Repository } from 'typeorm';
|
|
||||||
import { TABLE_NAME } from 'src/core/strings/constants/table.constants';
|
|
||||||
import { SelectQueryBuilder } from 'typeorm';
|
|
||||||
import { EventBus } from '@nestjs/cqrs';
|
|
||||||
import { DataSchedulingChangeStatusEvent } from '../../entities/event/data-scheduling-change-status.event';
|
|
||||||
import { DataSchedulingLogModel } from '../../../data/models/data-scheduling-log.model';
|
|
||||||
|
|
||||||
@Injectable()
|
|
||||||
export class DataSchedulingManager {
|
|
||||||
@Inject()
|
|
||||||
protected userProvider: UserProvider;
|
|
||||||
|
|
||||||
constructor(
|
|
||||||
private eventBus: EventBus,
|
|
||||||
|
|
||||||
@InjectRepository(DataSchedulingDefaultModel)
|
|
||||||
private repository: Repository<DataSchedulingDefaultModel>,
|
|
||||||
|
|
||||||
@InjectRepository(DataSchedulingLogModel)
|
|
||||||
private repositoryLog: Repository<DataSchedulingLogModel>,
|
|
||||||
) {}
|
|
||||||
|
|
||||||
private getUser(): UsersSession {
|
|
||||||
try {
|
|
||||||
return this.userProvider?.user ?? BLANK_USER;
|
|
||||||
} catch (error) {
|
|
||||||
return BLANK_USER;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
get tableName(): string {
|
|
||||||
return TABLE_NAME.DATA_SCHEDULING_DEFAULT;
|
|
||||||
}
|
|
||||||
|
|
||||||
private queryBuilder(): SelectQueryBuilder<DataSchedulingDefaultModel> {
|
|
||||||
return this.repository.createQueryBuilder(this.tableName);
|
|
||||||
}
|
|
||||||
|
|
||||||
async update(
|
|
||||||
body: EditDataSchedulingDefaultDto,
|
|
||||||
): Promise<DataSchedulingDefaultEntity> {
|
|
||||||
if (body.default_value > 100) {
|
|
||||||
throw new Error('Value tidak boleh lebih dari 100.');
|
|
||||||
}
|
|
||||||
|
|
||||||
const userData = this.getUser();
|
|
||||||
const dateNow = new Date().getTime();
|
|
||||||
const existData = await this.queryBuilder().getOne();
|
|
||||||
|
|
||||||
const payload: DataSchedulingDefaultEntity = {
|
|
||||||
id: existData?.id,
|
|
||||||
default_value: body.default_value,
|
|
||||||
creator_id: userData.id as any,
|
|
||||||
creator_name: userData.name,
|
|
||||||
editor_id: userData.id as any,
|
|
||||||
editor_name: userData.name,
|
|
||||||
created_at: dateNow,
|
|
||||||
updated_at: dateNow,
|
|
||||||
};
|
|
||||||
|
|
||||||
const saveData = await this.repository.save(payload);
|
|
||||||
|
|
||||||
if (existData?.default_value !== saveData?.default_value) {
|
|
||||||
const description = existData?.id
|
|
||||||
? `<div><b>${saveData.editor_name}</b> changed the <b><i>Default Percentage</i></b> setting from <b><i>${existData.default_value}%</i></b> to <b><i>${saveData.default_value}%</i></b>.</div>`
|
|
||||||
: `<div><b>${saveData.creator_name}</b> created the <b><i>Default Percentage</i></b> setting with a value of <b><i>${saveData.default_value}%</i></b>.</div>`;
|
|
||||||
|
|
||||||
const logPayload: DataSchedulingLogEntity = {
|
|
||||||
type: SCHEDULING_LOG_TYPE_ENUM.DEFAULT_PERCENTAGE,
|
|
||||||
action: existData?.id
|
|
||||||
? SCHEDULING_LOG_ACTION_ENUM.UPDATE
|
|
||||||
: SCHEDULING_LOG_ACTION_ENUM.CREATE,
|
|
||||||
log_created_at: new Date().getTime(),
|
|
||||||
status: undefined,
|
|
||||||
|
|
||||||
data_id: saveData?.id,
|
|
||||||
creator_id: saveData?.creator_id,
|
|
||||||
creator_name: saveData?.creator_name,
|
|
||||||
editor_id: saveData?.editor_id,
|
|
||||||
editor_name: saveData?.editor_name,
|
|
||||||
created_at: saveData?.created_at,
|
|
||||||
updated_at: saveData?.updated_at,
|
|
||||||
default_value: saveData?.default_value,
|
|
||||||
description: description,
|
|
||||||
};
|
|
||||||
|
|
||||||
await this.repositoryLog.save(logPayload as any);
|
|
||||||
}
|
|
||||||
await this.publishEventUpdates();
|
|
||||||
return saveData;
|
|
||||||
}
|
|
||||||
|
|
||||||
async getData() {
|
|
||||||
return this.queryBuilder().getOne();
|
|
||||||
}
|
|
||||||
|
|
||||||
async publishEventUpdates() {
|
|
||||||
await this.eventBus.publish(
|
|
||||||
new DataSchedulingChangeStatusEvent({ data: null } as any),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
async setupActiveScheduling() {
|
|
||||||
await this.publishEventUpdates();
|
|
||||||
return { message: 'Success setup transaction schedule.' };
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -1,45 +0,0 @@
|
||||||
import { Injectable } from '@nestjs/common';
|
|
||||||
import { BaseDeleteManager } from 'src/core/modules/domain/usecase/managers/base-delete.manager';
|
|
||||||
import { DataSchedulingEntity } from '../../entities/data-scheduling.entity';
|
|
||||||
import {
|
|
||||||
EventTopics,
|
|
||||||
validateRelations,
|
|
||||||
} from 'src/core/strings/constants/interface.constants';
|
|
||||||
import { DataSchedulingModel } from '../../../data/models/data-scheduling.model';
|
|
||||||
import { DataSchedulingDeletedEvent } from '../../entities/event/data-scheduling-deleted.event';
|
|
||||||
|
|
||||||
@Injectable()
|
|
||||||
export class DeleteDataSchedulingManager extends BaseDeleteManager<DataSchedulingEntity> {
|
|
||||||
getResult(): string {
|
|
||||||
return `Success`;
|
|
||||||
}
|
|
||||||
|
|
||||||
async validateProcess(): Promise<void> {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
async beforeProcess(): Promise<void> {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
async afterProcess(): Promise<void> {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
get validateRelations(): validateRelations[] {
|
|
||||||
return [];
|
|
||||||
}
|
|
||||||
|
|
||||||
get entityTarget(): any {
|
|
||||||
return DataSchedulingModel;
|
|
||||||
}
|
|
||||||
|
|
||||||
get eventTopics(): EventTopics[] {
|
|
||||||
return [
|
|
||||||
{
|
|
||||||
topic: DataSchedulingDeletedEvent,
|
|
||||||
data: this.data,
|
|
||||||
},
|
|
||||||
];
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -1,59 +0,0 @@
|
||||||
import { Injectable, NotFoundException } from '@nestjs/common';
|
|
||||||
import { BaseDetailManager } from 'src/core/modules/domain/usecase/managers/base-detail.manager';
|
|
||||||
import { DataSchedulingEntity } from '../../entities/data-scheduling.entity';
|
|
||||||
import { RelationParam } from 'src/core/modules/domain/entities/base-filter.entity';
|
|
||||||
import { decryptionTotal } from '../../../infrastructure/helpers';
|
|
||||||
|
|
||||||
@Injectable()
|
|
||||||
export class DetailDataSchedulingManager extends BaseDetailManager<DataSchedulingEntity> {
|
|
||||||
async prepareData(): Promise<void> {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
async beforeProcess(): Promise<void> {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
async afterProcess(): Promise<void> {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
get relations(): RelationParam {
|
|
||||||
return {
|
|
||||||
joinRelations: [],
|
|
||||||
selectRelations: [],
|
|
||||||
countRelations: [],
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
get selects(): string[] {
|
|
||||||
return [
|
|
||||||
`${this.tableName}.id`,
|
|
||||||
`${this.tableName}.status`,
|
|
||||||
`${this.tableName}.name`,
|
|
||||||
`${this.tableName}.indexing_key`,
|
|
||||||
`${this.tableName}.schedule_date_from`,
|
|
||||||
`${this.tableName}.schedule_date_to`,
|
|
||||||
`${this.tableName}.created_at`,
|
|
||||||
`${this.tableName}.creator_name`,
|
|
||||||
`${this.tableName}.updated_at`,
|
|
||||||
`${this.tableName}.editor_name`,
|
|
||||||
];
|
|
||||||
}
|
|
||||||
|
|
||||||
get setFindProperties(): any {
|
|
||||||
return {
|
|
||||||
id: this.dataId,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
getResult(): DataSchedulingEntity {
|
|
||||||
if (!this.result) throw new NotFoundException('Data not found.');
|
|
||||||
|
|
||||||
const total = decryptionTotal(this.result.indexing_key as string);
|
|
||||||
return {
|
|
||||||
...this.result,
|
|
||||||
indexing_key: total,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -1,45 +0,0 @@
|
||||||
import { Injectable } from '@nestjs/common';
|
|
||||||
import { BaseUpdateStatusManager } from 'src/core/modules/domain/usecase/managers/base-update-status.manager';
|
|
||||||
import { DataSchedulingEntity } from '../../entities/data-scheduling.entity';
|
|
||||||
import {
|
|
||||||
EventTopics,
|
|
||||||
validateRelations,
|
|
||||||
} from 'src/core/strings/constants/interface.constants';
|
|
||||||
import { DataSchedulingModel } from '../../../data/models/data-scheduling.model';
|
|
||||||
import { DataSchedulingChangeStatusEvent } from '../../entities/event/data-scheduling-change-status.event';
|
|
||||||
|
|
||||||
@Injectable()
|
|
||||||
export class InactiveDataSchedulingManager extends BaseUpdateStatusManager<DataSchedulingEntity> {
|
|
||||||
getResult(): string {
|
|
||||||
return `Success inactive data ${this.result.name}`;
|
|
||||||
}
|
|
||||||
|
|
||||||
async validateProcess(): Promise<void> {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
async beforeProcess(): Promise<void> {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
async afterProcess(): Promise<void> {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
get validateRelations(): validateRelations[] {
|
|
||||||
return [];
|
|
||||||
}
|
|
||||||
|
|
||||||
get entityTarget(): any {
|
|
||||||
return DataSchedulingModel;
|
|
||||||
}
|
|
||||||
|
|
||||||
get eventTopics(): EventTopics[] {
|
|
||||||
return [
|
|
||||||
{
|
|
||||||
topic: DataSchedulingChangeStatusEvent,
|
|
||||||
data: this.data,
|
|
||||||
},
|
|
||||||
];
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -1,116 +0,0 @@
|
||||||
import { Injectable } from '@nestjs/common';
|
|
||||||
import { BaseIndexManager } from 'src/core/modules/domain/usecase/managers/base-index.manager';
|
|
||||||
import { DataSchedulingLogEntity } from '../../entities/data-scheduling.entity';
|
|
||||||
import { SelectQueryBuilder } from 'typeorm';
|
|
||||||
import {
|
|
||||||
Param,
|
|
||||||
RelationParam,
|
|
||||||
} from 'src/core/modules/domain/entities/base-filter.entity';
|
|
||||||
import { PaginationResponse } from 'src/core/response/domain/ok-response.interface';
|
|
||||||
import { decryptionTotal } from '../../../infrastructure/helpers';
|
|
||||||
|
|
||||||
@Injectable()
|
|
||||||
export class IndexDataSchedulingLogManager extends BaseIndexManager<DataSchedulingLogEntity> {
|
|
||||||
async prepareData(): Promise<void> {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
async beforeProcess(): Promise<void> {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
async afterProcess(): Promise<void> {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
get relations(): RelationParam {
|
|
||||||
return {
|
|
||||||
joinRelations: [],
|
|
||||||
selectRelations: [],
|
|
||||||
countRelations: [],
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
get selects(): string[] {
|
|
||||||
return [
|
|
||||||
`${this.tableName}.id`,
|
|
||||||
`${this.tableName}.type`,
|
|
||||||
`${this.tableName}.action`,
|
|
||||||
`${this.tableName}.log_created_at`,
|
|
||||||
`${this.tableName}.data_id`,
|
|
||||||
`${this.tableName}.default_value`,
|
|
||||||
`${this.tableName}.description`,
|
|
||||||
|
|
||||||
`${this.tableName}.status`,
|
|
||||||
`${this.tableName}.name`,
|
|
||||||
`${this.tableName}.indexing_key`,
|
|
||||||
`${this.tableName}.schedule_date_from`,
|
|
||||||
`${this.tableName}.schedule_date_to`,
|
|
||||||
`${this.tableName}.created_at`,
|
|
||||||
`${this.tableName}.creator_name`,
|
|
||||||
`${this.tableName}.updated_at`,
|
|
||||||
`${this.tableName}.editor_name`,
|
|
||||||
];
|
|
||||||
}
|
|
||||||
|
|
||||||
get specificFilter(): Param[] {
|
|
||||||
return [
|
|
||||||
{
|
|
||||||
cols: `${this.tableName}.name`,
|
|
||||||
data: this.filterParam.names,
|
|
||||||
},
|
|
||||||
];
|
|
||||||
}
|
|
||||||
|
|
||||||
setQueryFilter(
|
|
||||||
queryBuilder: SelectQueryBuilder<DataSchedulingLogEntity>,
|
|
||||||
): SelectQueryBuilder<DataSchedulingLogEntity> {
|
|
||||||
if (this.filterParam.schedule_date_from) {
|
|
||||||
const dateFrom = this.filterParam.schedule_date_from;
|
|
||||||
queryBuilder.andWhere('schedule_date_from >= :dateFrom', {
|
|
||||||
dateFrom: dateFrom,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
if (this.filterParam.schedule_date_to) {
|
|
||||||
const dateTo = this.filterParam.schedule_date_to;
|
|
||||||
queryBuilder.andWhere('schedule_date_to <= :dateTo', {
|
|
||||||
dateTo: dateTo,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
if (this.filterParam.log_created_from && this.filterParam.log_created_to) {
|
|
||||||
const dateFrom = this.filterParam.log_created_from;
|
|
||||||
const dateTo = this.filterParam.log_created_to;
|
|
||||||
|
|
||||||
queryBuilder.andWhere('log_created_at BETWEEN :dateFrom AND :dateTo', {
|
|
||||||
dateFrom: dateFrom,
|
|
||||||
dateTo: dateTo,
|
|
||||||
});
|
|
||||||
} else if (this.filterParam.log_created_from) {
|
|
||||||
const dateFrom = this.filterParam.log_created_from;
|
|
||||||
queryBuilder.andWhere('log_created_at >= :dateFrom', {
|
|
||||||
dateFrom: dateFrom,
|
|
||||||
});
|
|
||||||
} else if (this.filterParam.log_created_to) {
|
|
||||||
const dateTo = this.filterParam.log_created_to;
|
|
||||||
queryBuilder.andWhere('log_created_at <= :dateTo', {
|
|
||||||
dateTo: dateTo,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
return queryBuilder;
|
|
||||||
}
|
|
||||||
|
|
||||||
getResult(): PaginationResponse<DataSchedulingLogEntity> {
|
|
||||||
const data = this.result.data;
|
|
||||||
|
|
||||||
return {
|
|
||||||
...this.result,
|
|
||||||
data: data.map((item) => {
|
|
||||||
const total = decryptionTotal(item.indexing_key as string);
|
|
||||||
return { ...item, indexing_key: total };
|
|
||||||
}),
|
|
||||||
};
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -1,88 +0,0 @@
|
||||||
import { Injectable } from '@nestjs/common';
|
|
||||||
import { BaseIndexManager } from 'src/core/modules/domain/usecase/managers/base-index.manager';
|
|
||||||
import { DataSchedulingEntity } from '../../entities/data-scheduling.entity';
|
|
||||||
import { SelectQueryBuilder } from 'typeorm';
|
|
||||||
import {
|
|
||||||
Param,
|
|
||||||
RelationParam,
|
|
||||||
} from 'src/core/modules/domain/entities/base-filter.entity';
|
|
||||||
import { PaginationResponse } from 'src/core/response/domain/ok-response.interface';
|
|
||||||
import { decryptionTotal } from '../../../infrastructure/helpers';
|
|
||||||
|
|
||||||
@Injectable()
|
|
||||||
export class IndexDataSchedulingManager extends BaseIndexManager<DataSchedulingEntity> {
|
|
||||||
async prepareData(): Promise<void> {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
async beforeProcess(): Promise<void> {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
async afterProcess(): Promise<void> {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
get relations(): RelationParam {
|
|
||||||
return {
|
|
||||||
joinRelations: [],
|
|
||||||
selectRelations: [],
|
|
||||||
countRelations: [],
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
get selects(): string[] {
|
|
||||||
return [
|
|
||||||
`${this.tableName}.id`,
|
|
||||||
`${this.tableName}.status`,
|
|
||||||
`${this.tableName}.name`,
|
|
||||||
`${this.tableName}.indexing_key`,
|
|
||||||
`${this.tableName}.schedule_date_from`,
|
|
||||||
`${this.tableName}.schedule_date_to`,
|
|
||||||
`${this.tableName}.created_at`,
|
|
||||||
`${this.tableName}.creator_name`,
|
|
||||||
`${this.tableName}.updated_at`,
|
|
||||||
`${this.tableName}.editor_name`,
|
|
||||||
];
|
|
||||||
}
|
|
||||||
|
|
||||||
get specificFilter(): Param[] {
|
|
||||||
return [
|
|
||||||
{
|
|
||||||
cols: `${this.tableName}.name`,
|
|
||||||
data: this.filterParam.names,
|
|
||||||
},
|
|
||||||
];
|
|
||||||
}
|
|
||||||
|
|
||||||
setQueryFilter(
|
|
||||||
queryBuilder: SelectQueryBuilder<DataSchedulingEntity>,
|
|
||||||
): SelectQueryBuilder<DataSchedulingEntity> {
|
|
||||||
if (this.filterParam.schedule_date_from) {
|
|
||||||
const dateFrom = this.filterParam.schedule_date_from;
|
|
||||||
queryBuilder.andWhere('schedule_date_from >= :dateFrom', {
|
|
||||||
dateFrom: dateFrom,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
if (this.filterParam.schedule_date_to) {
|
|
||||||
const dateTo = this.filterParam.schedule_date_to;
|
|
||||||
queryBuilder.andWhere('schedule_date_to <= :dateTo', {
|
|
||||||
dateTo: dateTo,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
return queryBuilder;
|
|
||||||
}
|
|
||||||
|
|
||||||
getResult(): PaginationResponse<DataSchedulingEntity> {
|
|
||||||
const data = this.result.data;
|
|
||||||
|
|
||||||
return {
|
|
||||||
...this.result,
|
|
||||||
data: data.map((item) => {
|
|
||||||
const total = decryptionTotal(item.indexing_key as string);
|
|
||||||
return { ...item, indexing_key: total };
|
|
||||||
}),
|
|
||||||
};
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -1,76 +0,0 @@
|
||||||
import { Injectable } from '@nestjs/common';
|
|
||||||
import { BaseUpdateManager } from 'src/core/modules/domain/usecase/managers/base-update.manager';
|
|
||||||
import { DataSchedulingEntity } from '../../entities/data-scheduling.entity';
|
|
||||||
import { DataSchedulingModel } from '../../../data/models/data-scheduling.model';
|
|
||||||
import { DataSchedulingUpdatedEvent } from '../../entities/event/data-scheduling-updated.event';
|
|
||||||
import {
|
|
||||||
EventTopics,
|
|
||||||
columnUniques,
|
|
||||||
validateRelations,
|
|
||||||
} from 'src/core/strings/constants/interface.constants';
|
|
||||||
import { encryptionTotal } from '../../../infrastructure/helpers';
|
|
||||||
|
|
||||||
@Injectable()
|
|
||||||
export class UpdateDataSchedulingManager extends BaseUpdateManager<DataSchedulingEntity> {
|
|
||||||
async validateProcess(): Promise<void> {
|
|
||||||
const total = this.data.indexing_key;
|
|
||||||
|
|
||||||
if (total > 100) {
|
|
||||||
throw new Error('Maksimal nilai total adalah 100.');
|
|
||||||
}
|
|
||||||
|
|
||||||
const queryBuilder = this.dataService
|
|
||||||
.getRepository()
|
|
||||||
.createQueryBuilder(this.tableName);
|
|
||||||
|
|
||||||
const overlapping = await queryBuilder
|
|
||||||
.where(`${this.tableName}.schedule_date_from <= :schedule_date_to`, {
|
|
||||||
schedule_date_to: this.data.schedule_date_to,
|
|
||||||
})
|
|
||||||
.andWhere(`${this.tableName}.schedule_date_to >= :schedule_date_from`, {
|
|
||||||
schedule_date_from: this.data.schedule_date_from,
|
|
||||||
})
|
|
||||||
.andWhere(`${this.tableName}.id != :id`, { id: this.dataId ?? null })
|
|
||||||
.getOne();
|
|
||||||
|
|
||||||
// Validation date
|
|
||||||
if (overlapping) {
|
|
||||||
throw new Error('Tanggal yang dimasukkan tidak boleh sama.');
|
|
||||||
} else {
|
|
||||||
//Encryption total data
|
|
||||||
Object.assign(this.data, {
|
|
||||||
indexing_key: encryptionTotal(total),
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
async beforeProcess(): Promise<void> {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
async afterProcess(): Promise<void> {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
get validateRelations(): validateRelations[] {
|
|
||||||
return [];
|
|
||||||
}
|
|
||||||
|
|
||||||
get uniqueColumns(): columnUniques[] {
|
|
||||||
return [{ column: 'name' }];
|
|
||||||
}
|
|
||||||
|
|
||||||
get entityTarget(): any {
|
|
||||||
return DataSchedulingModel;
|
|
||||||
}
|
|
||||||
|
|
||||||
get eventTopics(): EventTopics[] {
|
|
||||||
return [
|
|
||||||
{
|
|
||||||
topic: DataSchedulingUpdatedEvent,
|
|
||||||
},
|
|
||||||
];
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -1,148 +0,0 @@
|
||||||
import {
|
|
||||||
Body,
|
|
||||||
Controller,
|
|
||||||
Delete,
|
|
||||||
Get,
|
|
||||||
Param,
|
|
||||||
Patch,
|
|
||||||
Post,
|
|
||||||
Put,
|
|
||||||
UseGuards,
|
|
||||||
} from '@nestjs/common';
|
|
||||||
import { DataSchedulingDataOrchestrator } from '../domain/usecases/data-scheduling-data.orchestrator';
|
|
||||||
import {
|
|
||||||
CreateDataSchedulingDto,
|
|
||||||
EditDataSchedulingDto,
|
|
||||||
EditDataSchedulingDefaultDto,
|
|
||||||
DeleteDataSchedulingLogDto,
|
|
||||||
} from './dto/data-scheduling.dto';
|
|
||||||
import { MODULE_NAME } from 'src/core/strings/constants/module.constants';
|
|
||||||
import { ApiBearerAuth, ApiTags } from '@nestjs/swagger';
|
|
||||||
import {
|
|
||||||
DataSchedulingDefaultEntity,
|
|
||||||
DataSchedulingEntity,
|
|
||||||
} from '../domain/entities/data-scheduling.entity';
|
|
||||||
import { BatchResult } from 'src/core/response/domain/ok-response.interface';
|
|
||||||
import { BatchIdsDto } from 'src/core/modules/infrastructure/dto/base-batch.dto';
|
|
||||||
import { ExcludePrivilege, Public } from 'src/core/guards';
|
|
||||||
import { SetupSchedulingGuard } from './guards/setup-scheduling.guard';
|
|
||||||
import { DataSchedulingManager } from '../domain/usecases/managers/data-scheduling-default.manager';
|
|
||||||
import { DataSchedulingLogDataService } from '../data/services/data-scheduling-log-data.service';
|
|
||||||
|
|
||||||
@ApiTags(`${MODULE_NAME.DATA_SCHEDULING.split('-').join(' ')} - data`)
|
|
||||||
@Controller(`v1/${MODULE_NAME.DATA_SCHEDULING}`)
|
|
||||||
@Public(false)
|
|
||||||
@ApiBearerAuth('JWT')
|
|
||||||
export class DataSchedulingDataController {
|
|
||||||
constructor(private orchestrator: DataSchedulingDataOrchestrator) {}
|
|
||||||
|
|
||||||
@Post()
|
|
||||||
async create(
|
|
||||||
@Body() data: CreateDataSchedulingDto,
|
|
||||||
): Promise<DataSchedulingEntity> {
|
|
||||||
return await this.orchestrator.create(data);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Put('/batch-delete')
|
|
||||||
async batchDeleted(@Body() body: BatchIdsDto): Promise<BatchResult> {
|
|
||||||
return await this.orchestrator.batchDelete(body.ids);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Patch(':id/active')
|
|
||||||
async active(@Param('id') dataId: string): Promise<string> {
|
|
||||||
return await this.orchestrator.active(dataId);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Put('/batch-active')
|
|
||||||
async batchActive(@Body() body: BatchIdsDto): Promise<BatchResult> {
|
|
||||||
return await this.orchestrator.batchActive(body.ids);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Patch(':id/confirm')
|
|
||||||
async confirm(@Param('id') dataId: string): Promise<string> {
|
|
||||||
return await this.orchestrator.confirm(dataId);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Put('/batch-confirm')
|
|
||||||
async batchConfirm(@Body() body: BatchIdsDto): Promise<BatchResult> {
|
|
||||||
return await this.orchestrator.batchConfirm(body.ids);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Patch(':id/inactive')
|
|
||||||
async inactive(@Param('id') dataId: string): Promise<string> {
|
|
||||||
return await this.orchestrator.inactive(dataId);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Put('/batch-inactive')
|
|
||||||
async batchInactive(@Body() body: BatchIdsDto): Promise<BatchResult> {
|
|
||||||
return await this.orchestrator.batchInactive(body.ids);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Put(':id')
|
|
||||||
async update(
|
|
||||||
@Param('id') dataId: string,
|
|
||||||
@Body() data: EditDataSchedulingDto,
|
|
||||||
): Promise<DataSchedulingEntity> {
|
|
||||||
return await this.orchestrator.update(dataId, data);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Delete(':id')
|
|
||||||
async delete(@Param('id') dataId: string): Promise<string> {
|
|
||||||
return await this.orchestrator.delete(dataId);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@ApiTags(
|
|
||||||
`${MODULE_NAME.DATA_SCHEDULING_DEFAULT.split('-').join(' ')} default - Data`,
|
|
||||||
)
|
|
||||||
@Controller(`v1/${MODULE_NAME.DATA_SCHEDULING_DEFAULT}`)
|
|
||||||
@Public(false)
|
|
||||||
@ApiBearerAuth('JWT')
|
|
||||||
export class DataSchedulingDefaultController {
|
|
||||||
constructor(private manager: DataSchedulingManager) {}
|
|
||||||
@Post()
|
|
||||||
async create(
|
|
||||||
@Body() data: EditDataSchedulingDefaultDto,
|
|
||||||
): Promise<DataSchedulingDefaultEntity> {
|
|
||||||
return await this.manager.update(data);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Get()
|
|
||||||
async get(): Promise<DataSchedulingDefaultEntity> {
|
|
||||||
return await this.manager.getData();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@ApiTags(
|
|
||||||
`${MODULE_NAME.DATA_SCHEDULING_SETUP.split('-').join(' ')} setup - Data`,
|
|
||||||
)
|
|
||||||
@Controller(`v1/${MODULE_NAME.DATA_SCHEDULING_SETUP}`)
|
|
||||||
@Public(true)
|
|
||||||
@ApiBearerAuth('JWT')
|
|
||||||
export class DataSchedulingSetupController {
|
|
||||||
constructor(private manager: DataSchedulingManager) {}
|
|
||||||
|
|
||||||
@Post()
|
|
||||||
@ExcludePrivilege()
|
|
||||||
@UseGuards(SetupSchedulingGuard)
|
|
||||||
async setup(): Promise<{ message: string }> {
|
|
||||||
return this.manager.setupActiveScheduling();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@ApiTags(`${MODULE_NAME.DATA_SCHEDULING_LOG.split('-').join(' ')} log - Data`)
|
|
||||||
@Controller(`v1/${MODULE_NAME.DATA_SCHEDULING_LOG}`)
|
|
||||||
@Public(true)
|
|
||||||
@ApiBearerAuth('JWT')
|
|
||||||
export class DataSchedulingDataLogController {
|
|
||||||
constructor(private service: DataSchedulingLogDataService) {}
|
|
||||||
|
|
||||||
@Post('delete-range')
|
|
||||||
@ExcludePrivilege()
|
|
||||||
@UseGuards(SetupSchedulingGuard)
|
|
||||||
async setup(
|
|
||||||
@Body() data: DeleteDataSchedulingLogDto,
|
|
||||||
): Promise<{ message: string }> {
|
|
||||||
return this.service.deleteRange(data.log_created_from, data.log_created_to);
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -1,53 +0,0 @@
|
||||||
import { Controller, Get, Param, Query } from '@nestjs/common';
|
|
||||||
import {
|
|
||||||
FilterDataSchedulingDto,
|
|
||||||
FilterDataSchedulingLogDto,
|
|
||||||
} from './dto/filter-data-scheduling.dto';
|
|
||||||
import { Pagination } from 'src/core/response';
|
|
||||||
import { PaginationResponse } from 'src/core/response/domain/ok-response.interface';
|
|
||||||
import {
|
|
||||||
DataSchedulingEntity,
|
|
||||||
DataSchedulingLogEntity,
|
|
||||||
} from '../domain/entities/data-scheduling.entity';
|
|
||||||
import { DataSchedulingReadOrchestrator } from '../domain/usecases/data-scheduling-read.orchestrator';
|
|
||||||
import { ApiBearerAuth, ApiTags } from '@nestjs/swagger';
|
|
||||||
import { MODULE_NAME } from 'src/core/strings/constants/module.constants';
|
|
||||||
import { ExcludePrivilege, Public } from 'src/core/guards';
|
|
||||||
|
|
||||||
@ApiTags(`${MODULE_NAME.DATA_SCHEDULING.split('-').join(' ')} - read`)
|
|
||||||
@Controller(`v1/${MODULE_NAME.DATA_SCHEDULING}`)
|
|
||||||
@Public(false)
|
|
||||||
@ApiBearerAuth('JWT')
|
|
||||||
export class DataSchedulingReadController {
|
|
||||||
constructor(private orchestrator: DataSchedulingReadOrchestrator) {}
|
|
||||||
|
|
||||||
@Get()
|
|
||||||
@Pagination()
|
|
||||||
async index(
|
|
||||||
@Query() params: FilterDataSchedulingDto,
|
|
||||||
): Promise<PaginationResponse<DataSchedulingEntity>> {
|
|
||||||
return await this.orchestrator.index(params);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Get(':id')
|
|
||||||
async detail(@Param('id') id: string): Promise<DataSchedulingEntity> {
|
|
||||||
return await this.orchestrator.detail(id);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@ApiTags(`${MODULE_NAME.DATA_SCHEDULING_LOG.split('-').join(' ')} - read`)
|
|
||||||
@Controller(`v1/${MODULE_NAME.DATA_SCHEDULING_LOG}`)
|
|
||||||
@Public(false)
|
|
||||||
@ApiBearerAuth('JWT')
|
|
||||||
export class DataSchedulingLogReadController {
|
|
||||||
constructor(private orchestrator: DataSchedulingReadOrchestrator) {}
|
|
||||||
|
|
||||||
@Get()
|
|
||||||
@Pagination()
|
|
||||||
@ExcludePrivilege()
|
|
||||||
async index(
|
|
||||||
@Query() params: FilterDataSchedulingLogDto,
|
|
||||||
): Promise<PaginationResponse<DataSchedulingLogEntity>> {
|
|
||||||
return await this.orchestrator.indexLog(params);
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -1,98 +0,0 @@
|
||||||
import { BaseStatusDto } from 'src/core/modules/infrastructure/dto/base-status.dto';
|
|
||||||
import {
|
|
||||||
DataSchedulingDefaultEntity,
|
|
||||||
DataSchedulingEntity,
|
|
||||||
} from '../../domain/entities/data-scheduling.entity';
|
|
||||||
import { IsString, ValidateIf } from 'class-validator';
|
|
||||||
import { ApiProperty } from '@nestjs/swagger';
|
|
||||||
import { BaseCoreDto } from 'src/core/modules/infrastructure/dto/base-core.dto';
|
|
||||||
import { Transform } from 'class-transformer';
|
|
||||||
import { BaseDto } from 'src/core/modules/infrastructure/dto/base.dto';
|
|
||||||
|
|
||||||
export class CreateDataSchedulingDto
|
|
||||||
extends BaseStatusDto
|
|
||||||
implements DataSchedulingEntity
|
|
||||||
{
|
|
||||||
@ApiProperty({ name: 'name', required: true, example: 'Morning' })
|
|
||||||
@IsString()
|
|
||||||
name: string;
|
|
||||||
|
|
||||||
@ApiProperty({ type: 'integer', required: true, example: 80 })
|
|
||||||
@Transform((body) => {
|
|
||||||
return typeof body.value == 'string' ? Number(body.value) : body.value;
|
|
||||||
})
|
|
||||||
@ValidateIf((body) => body.indexing_key)
|
|
||||||
indexing_key: number;
|
|
||||||
|
|
||||||
@ApiProperty({
|
|
||||||
type: Date,
|
|
||||||
required: true,
|
|
||||||
example: '2024-01-01',
|
|
||||||
})
|
|
||||||
schedule_date_from: Date;
|
|
||||||
|
|
||||||
@ApiProperty({
|
|
||||||
type: Date,
|
|
||||||
required: true,
|
|
||||||
example: '2024-01-02',
|
|
||||||
})
|
|
||||||
schedule_date_to: Date;
|
|
||||||
}
|
|
||||||
|
|
||||||
export class EditDataSchedulingDto
|
|
||||||
extends BaseStatusDto
|
|
||||||
implements DataSchedulingEntity
|
|
||||||
{
|
|
||||||
@ApiProperty({ name: 'name', example: 'Morning' })
|
|
||||||
@IsString()
|
|
||||||
@ValidateIf((body) => body.name)
|
|
||||||
name: string;
|
|
||||||
|
|
||||||
@ApiProperty({ type: 'integer', required: true, example: 80 })
|
|
||||||
@Transform((body) => {
|
|
||||||
return typeof body.value == 'string' ? Number(body.value) : body.value;
|
|
||||||
})
|
|
||||||
@ValidateIf((body) => body.indexing_key)
|
|
||||||
indexing_key: number;
|
|
||||||
|
|
||||||
@ApiProperty({
|
|
||||||
type: Date,
|
|
||||||
required: true,
|
|
||||||
example: '2025-01-01',
|
|
||||||
})
|
|
||||||
schedule_date_from: Date;
|
|
||||||
|
|
||||||
@ApiProperty({
|
|
||||||
type: Date,
|
|
||||||
required: true,
|
|
||||||
example: '2025-01-02',
|
|
||||||
})
|
|
||||||
schedule_date_to: Date;
|
|
||||||
}
|
|
||||||
|
|
||||||
export class EditDataSchedulingDefaultDto
|
|
||||||
extends BaseDto
|
|
||||||
implements DataSchedulingDefaultEntity
|
|
||||||
{
|
|
||||||
@ApiProperty({ type: 'integer', required: true })
|
|
||||||
@Transform((body) => {
|
|
||||||
return typeof body.value == 'string' ? Number(body.value) : body.value;
|
|
||||||
})
|
|
||||||
@ValidateIf((body) => body.default_value)
|
|
||||||
default_value: number;
|
|
||||||
}
|
|
||||||
|
|
||||||
export class SetupDataSchedulingDto {
|
|
||||||
// @ApiProperty({ type: 'string', required: true, example: '2025-01-01' })
|
|
||||||
// date: Date;
|
|
||||||
}
|
|
||||||
|
|
||||||
export class DeleteDataSchedulingLogDto {
|
|
||||||
@ApiProperty({ type: Number, required: true })
|
|
||||||
@ValidateIf((body) => body.log_created_from)
|
|
||||||
log_created_from: number;
|
|
||||||
|
|
||||||
@ApiProperty({ type: Number, required: true })
|
|
||||||
@ValidateIf((body) => body.log_created_to)
|
|
||||||
log_created_to: number;
|
|
||||||
}
|
|
|
@ -1,44 +0,0 @@
|
||||||
import { BaseFilterDto } from 'src/core/modules/infrastructure/dto/base-filter.dto';
|
|
||||||
import { FilterDataSchedulingEntity } from '../../domain/entities/filter-data-scheduling.entity';
|
|
||||||
import { ApiProperty } from '@nestjs/swagger';
|
|
||||||
import { ValidateIf } from 'class-validator';
|
|
||||||
|
|
||||||
export class FilterDataSchedulingDto
|
|
||||||
extends BaseFilterDto
|
|
||||||
implements FilterDataSchedulingEntity
|
|
||||||
{
|
|
||||||
@ApiProperty({ type: 'string', required: false })
|
|
||||||
@ValidateIf((body) => body.schedule_date_from)
|
|
||||||
schedule_date_from: Date;
|
|
||||||
|
|
||||||
@ApiProperty({ type: 'string', required: false })
|
|
||||||
@ValidateIf((body) => body.schedule_date_to)
|
|
||||||
schedule_date_to: Date;
|
|
||||||
}
|
|
||||||
|
|
||||||
export class FilterDataSchedulingLogDto
|
|
||||||
extends BaseFilterDto
|
|
||||||
implements FilterDataSchedulingEntity
|
|
||||||
{
|
|
||||||
@ApiProperty({ type: 'string', required: false })
|
|
||||||
@ValidateIf((body) => body.schedule_date_from)
|
|
||||||
schedule_date_from: Date;
|
|
||||||
|
|
||||||
@ApiProperty({ type: 'string', required: false })
|
|
||||||
@ValidateIf((body) => body.schedule_date_to)
|
|
||||||
schedule_date_to: Date;
|
|
||||||
|
|
||||||
@ApiProperty({ type: Number, required: false })
|
|
||||||
@ValidateIf((body) => body.log_created_from)
|
|
||||||
log_created_from: number;
|
|
||||||
|
|
||||||
@ApiProperty({ type: Number, required: false })
|
|
||||||
@ValidateIf((body) => body.log_created_to)
|
|
||||||
log_created_to: number;
|
|
||||||
}
|
|
||||||
|
|
||||||
export class FilterActiveDataSchedulingDto {
|
|
||||||
// @ApiProperty({ type: 'string', required: true })
|
|
||||||
// @ValidateIf((body) => body.schedule_date_from)
|
|
||||||
// date: Date;
|
|
||||||
}
|
|
|
@ -1,40 +0,0 @@
|
||||||
import {
|
|
||||||
CanActivate,
|
|
||||||
ExecutionContext,
|
|
||||||
Injectable,
|
|
||||||
UnprocessableEntityException,
|
|
||||||
} from '@nestjs/common';
|
|
||||||
import { JwtService } from '@nestjs/jwt';
|
|
||||||
|
|
||||||
@Injectable()
|
|
||||||
export class SetupSchedulingGuard implements CanActivate {
|
|
||||||
constructor(private readonly jwtService: JwtService) {}
|
|
||||||
|
|
||||||
async canActivate(context: ExecutionContext): Promise<boolean> {
|
|
||||||
const request = context.switchToHttp().getRequest();
|
|
||||||
const jwtAuth = request.headers['authorization'];
|
|
||||||
const setupAuth = request.headers['x-setup-authorization'];
|
|
||||||
|
|
||||||
if (setupAuth) {
|
|
||||||
try {
|
|
||||||
const setupKey = process.env.SETUP_SCHEDULING_KEY;
|
|
||||||
if (setupAuth === setupKey) return true;
|
|
||||||
else new UnprocessableEntityException('Setup Authorization Not Found.');
|
|
||||||
} catch (err) {
|
|
||||||
throw new UnprocessableEntityException('Invalid authentication.');
|
|
||||||
}
|
|
||||||
} else if (jwtAuth && jwtAuth.startsWith('Bearer ')) {
|
|
||||||
const token = jwtAuth.split(' ')[1];
|
|
||||||
try {
|
|
||||||
const payload = await this.jwtService.verifyAsync(token);
|
|
||||||
if (payload) return true;
|
|
||||||
else new UnprocessableEntityException('Setup Authorization Not Found.');
|
|
||||||
return true;
|
|
||||||
} catch (err) {
|
|
||||||
throw new UnprocessableEntityException('Invalid JWT token');
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
throw new UnprocessableEntityException('Invalid authentication');
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -1,9 +0,0 @@
|
||||||
import { EncryptionHelper } from 'src/modules/transaction/sales-price-formula/domain/helpers/encryption.helper';
|
|
||||||
|
|
||||||
export function encryptionTotal(total: number): string {
|
|
||||||
return EncryptionHelper.encrypt(btoa(total.toString()));
|
|
||||||
}
|
|
||||||
|
|
||||||
export function decryptionTotal(total: string): number {
|
|
||||||
return Number(atob(EncryptionHelper.decrypt(total)));
|
|
||||||
}
|
|
|
@ -10,7 +10,7 @@ import { TypeOrmModule } from '@nestjs/typeorm';
|
||||||
import { CONNECTION_NAME } from 'src/core/strings/constants/base.constants';
|
import { CONNECTION_NAME } from 'src/core/strings/constants/base.constants';
|
||||||
import { TransactionItemModel } from 'src/modules/transaction/transaction/data/models/transaction-item.model';
|
import { TransactionItemModel } from 'src/modules/transaction/transaction/data/models/transaction-item.model';
|
||||||
import { TransactionTaxModel } from 'src/modules/transaction/transaction/data/models/transaction-tax.model';
|
import { TransactionTaxModel } from 'src/modules/transaction/transaction/data/models/transaction-tax.model';
|
||||||
import { CouchModule } from 'src/modules/configuration/couch/couch.module';
|
|
||||||
@Module({
|
@Module({
|
||||||
imports: [
|
imports: [
|
||||||
ConfigModule.forRoot(),
|
ConfigModule.forRoot(),
|
||||||
|
@ -19,7 +19,6 @@ import { CouchModule } from 'src/modules/configuration/couch/couch.module';
|
||||||
CONNECTION_NAME.DEFAULT,
|
CONNECTION_NAME.DEFAULT,
|
||||||
),
|
),
|
||||||
CqrsModule,
|
CqrsModule,
|
||||||
CouchModule,
|
|
||||||
],
|
],
|
||||||
controllers: [GoogleCalendarController],
|
controllers: [GoogleCalendarController],
|
||||||
providers: [
|
providers: [
|
||||||
|
|
|
@ -10,7 +10,7 @@ import { TransactionDataService } from 'src/modules/transaction/transaction/data
|
||||||
import { PaymentTransactionHandler } from './domain/handlers/payment-transaction.handler';
|
import { PaymentTransactionHandler } from './domain/handlers/payment-transaction.handler';
|
||||||
import { MailTemplateController } from './infrastructure/mail.controller';
|
import { MailTemplateController } from './infrastructure/mail.controller';
|
||||||
import { PdfMakeManager } from '../export/domain/managers/pdf-make.manager';
|
import { PdfMakeManager } from '../export/domain/managers/pdf-make.manager';
|
||||||
import { CouchModule } from '../couch/couch.module';
|
|
||||||
@Module({
|
@Module({
|
||||||
imports: [
|
imports: [
|
||||||
ConfigModule.forRoot(),
|
ConfigModule.forRoot(),
|
||||||
|
@ -19,7 +19,6 @@ import { CouchModule } from '../couch/couch.module';
|
||||||
CONNECTION_NAME.DEFAULT,
|
CONNECTION_NAME.DEFAULT,
|
||||||
),
|
),
|
||||||
CqrsModule,
|
CqrsModule,
|
||||||
CouchModule,
|
|
||||||
],
|
],
|
||||||
controllers: [MailTemplateController],
|
controllers: [MailTemplateController],
|
||||||
providers: [
|
providers: [
|
||||||
|
|
|
@ -21,19 +21,6 @@ export class MidtransService {
|
||||||
return diffInHours > 24;
|
return diffInHours > 24;
|
||||||
}
|
}
|
||||||
|
|
||||||
isCreatedMoreThan24HoursAgo(unixTimestamp) {
|
|
||||||
const date = moment.unix(unixTimestamp);
|
|
||||||
const now = moment();
|
|
||||||
const diffInHours = now.diff(date, 'hours');
|
|
||||||
return diffInHours > 24;
|
|
||||||
}
|
|
||||||
|
|
||||||
isBookingDateExpired(bookingDate) {
|
|
||||||
const bookingDateMoment = moment(bookingDate);
|
|
||||||
const today = moment().startOf('day');
|
|
||||||
return bookingDateMoment.isBefore(today);
|
|
||||||
}
|
|
||||||
|
|
||||||
get midtransInstance() {
|
get midtransInstance() {
|
||||||
return new Snap({
|
return new Snap({
|
||||||
isProduction: false,
|
isProduction: false,
|
||||||
|
@ -51,18 +38,16 @@ export class MidtransService {
|
||||||
const responses = [];
|
const responses = [];
|
||||||
|
|
||||||
for (const transaction of pendingIds) {
|
for (const transaction of pendingIds) {
|
||||||
const { id, booking_date, created_at } = transaction;
|
const { id, invoice_date } = transaction;
|
||||||
let status;
|
let status;
|
||||||
try {
|
try {
|
||||||
status = await this.getStatus(id);
|
status = await this.getStatus(id);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
status = {
|
status = {
|
||||||
order_id: id,
|
order_id: id,
|
||||||
transaction_status:
|
transaction_status: this.isMoreThan24HoursAgo(invoice_date)
|
||||||
this.isCreatedMoreThan24HoursAgo(created_at) ||
|
? 'cancel'
|
||||||
this.isBookingDateExpired(booking_date)
|
: 'pending',
|
||||||
? 'expired'
|
|
||||||
: 'pending',
|
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
responses.push(status);
|
responses.push(status);
|
||||||
|
|
|
@ -1,41 +0,0 @@
|
||||||
import { TABLE_NAME } from 'src/core/strings/constants/table.constants';
|
|
||||||
import {
|
|
||||||
OTP_ACTION_TYPE,
|
|
||||||
OTP_SOURCE,
|
|
||||||
OtpVerificationEntity,
|
|
||||||
} from '../../domain/entities/otp-verification.entity';
|
|
||||||
import { Column, Entity } from 'typeorm';
|
|
||||||
import { BaseModel } from 'src/core/modules/data/model/base.model';
|
|
||||||
|
|
||||||
@Entity(TABLE_NAME.OTP_VERIFICATIONS)
|
|
||||||
export class OtpVerificationModel
|
|
||||||
extends BaseModel<OtpVerificationEntity>
|
|
||||||
implements OtpVerificationEntity
|
|
||||||
{
|
|
||||||
@Column({ type: 'varchar', nullable: false })
|
|
||||||
otp_code: string;
|
|
||||||
|
|
||||||
@Column({ type: 'enum', enum: OTP_ACTION_TYPE })
|
|
||||||
action_type: OTP_ACTION_TYPE;
|
|
||||||
|
|
||||||
@Column({ type: 'varchar', nullable: true })
|
|
||||||
target_id: string;
|
|
||||||
|
|
||||||
@Column({ type: 'varchar', nullable: true })
|
|
||||||
reference: string;
|
|
||||||
|
|
||||||
@Column({ type: 'enum', enum: OTP_SOURCE })
|
|
||||||
source: OTP_SOURCE;
|
|
||||||
|
|
||||||
@Column({ default: false })
|
|
||||||
is_used: boolean;
|
|
||||||
|
|
||||||
@Column({ default: false })
|
|
||||||
is_replaced: boolean;
|
|
||||||
|
|
||||||
@Column({ type: 'bigint', nullable: false })
|
|
||||||
expired_at: number; // UNIX timestamp
|
|
||||||
|
|
||||||
@Column({ type: 'bigint', nullable: true })
|
|
||||||
verified_at: number; // UNIX timestamp or null
|
|
||||||
}
|
|
|
@ -1,25 +0,0 @@
|
||||||
import { TABLE_NAME } from 'src/core/strings/constants/table.constants';
|
|
||||||
import {
|
|
||||||
OTP_ACTION_TYPE,
|
|
||||||
OtpVerifierEntity,
|
|
||||||
} from '../../domain/entities/otp-verification.entity';
|
|
||||||
import { Column, Entity } from 'typeorm';
|
|
||||||
import { BaseModel } from 'src/core/modules/data/model/base.model';
|
|
||||||
|
|
||||||
@Entity(TABLE_NAME.OTP_VERIFIER)
|
|
||||||
export class OtpVerifierModel
|
|
||||||
extends BaseModel<OtpVerifierEntity>
|
|
||||||
implements OtpVerifierEntity
|
|
||||||
{
|
|
||||||
@Column({ type: 'varchar', nullable: true })
|
|
||||||
name: string;
|
|
||||||
|
|
||||||
@Column({ type: 'varchar', nullable: false })
|
|
||||||
phone_number: string;
|
|
||||||
|
|
||||||
@Column({ default: false })
|
|
||||||
is_all_action: boolean;
|
|
||||||
|
|
||||||
@Column({ type: 'enum', enum: OTP_ACTION_TYPE, array: true, nullable: true })
|
|
||||||
action_types: OTP_ACTION_TYPE[] | null;
|
|
||||||
}
|
|
|
@ -1,266 +0,0 @@
|
||||||
import { BadRequestException, Injectable } from '@nestjs/common';
|
|
||||||
import { InjectRepository } from '@nestjs/typeorm';
|
|
||||||
import { Repository } from 'typeorm';
|
|
||||||
import { OtpVerificationModel } from '../models/otp-verification.model';
|
|
||||||
import {
|
|
||||||
OTP_ACTION_TYPE,
|
|
||||||
OtpRequestEntity,
|
|
||||||
OtpVerificationEntity,
|
|
||||||
OtpVerifierEntity,
|
|
||||||
// OtpVerifierEntity,
|
|
||||||
OtpVerifyEntity,
|
|
||||||
} from '../../domain/entities/otp-verification.entity';
|
|
||||||
import * as moment from 'moment';
|
|
||||||
import { OtpService } from 'src/core/helpers/otp/otp-service';
|
|
||||||
import { TABLE_NAME } from 'src/core/strings/constants/table.constants';
|
|
||||||
import { WhatsappService } from 'src/services/whatsapp/whatsapp.service';
|
|
||||||
import { OtpVerifierModel } from '../models/otp-verifier.model';
|
|
||||||
|
|
||||||
@Injectable()
|
|
||||||
export class OtpVerificationService {
|
|
||||||
constructor(
|
|
||||||
@InjectRepository(OtpVerificationModel)
|
|
||||||
private readonly otpVerificationRepo: Repository<OtpVerificationModel>,
|
|
||||||
|
|
||||||
@InjectRepository(OtpVerifierModel)
|
|
||||||
private readonly otpVerifierRepo: Repository<OtpVerifierModel>,
|
|
||||||
) {}
|
|
||||||
|
|
||||||
private generateOtpExpiration(minutes = 5): number {
|
|
||||||
return moment().add(minutes, 'minutes').valueOf(); // epoch millis expired time
|
|
||||||
}
|
|
||||||
|
|
||||||
private generateResendAvailableAt(seconds = 60): number {
|
|
||||||
return moment().add(seconds, 'seconds').valueOf(); // epoch millis
|
|
||||||
}
|
|
||||||
|
|
||||||
private generateTimestamp(): number {
|
|
||||||
return moment().valueOf(); // epoch millis verification time (now)
|
|
||||||
}
|
|
||||||
|
|
||||||
private generateHeaderTemplate(payload) {
|
|
||||||
const label = payload.action_type;
|
|
||||||
|
|
||||||
// Optional logic to override label based on action type.
|
|
||||||
// e.g., if (payload.action_type === OTP_ACTION_TYPE.CONFIRM_TRANSACTION) label = 'CONFIRM_BOOKING_TRANSACTION'
|
|
||||||
|
|
||||||
const header = label.split('_').join(' ');
|
|
||||||
const type = label
|
|
||||||
.split('_')
|
|
||||||
.map((word) => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase())
|
|
||||||
.join(' ');
|
|
||||||
|
|
||||||
return { header, type };
|
|
||||||
}
|
|
||||||
|
|
||||||
private generateOTPMsgTemplate(payload) {
|
|
||||||
const { userRequest, newOtp } = payload;
|
|
||||||
const { header, type } = this.generateHeaderTemplate(newOtp);
|
|
||||||
|
|
||||||
const otpCode = newOtp?.otp_code;
|
|
||||||
const username = userRequest?.username;
|
|
||||||
|
|
||||||
return {
|
|
||||||
name: 'general_flow',
|
|
||||||
language: { code: 'id' },
|
|
||||||
components: [
|
|
||||||
{
|
|
||||||
type: 'header',
|
|
||||||
parameters: [
|
|
||||||
{
|
|
||||||
type: 'text',
|
|
||||||
parameter_name: 'header',
|
|
||||||
text: header,
|
|
||||||
},
|
|
||||||
],
|
|
||||||
},
|
|
||||||
{
|
|
||||||
type: 'body',
|
|
||||||
parameters: [
|
|
||||||
{
|
|
||||||
type: 'text',
|
|
||||||
parameter_name: 'name',
|
|
||||||
text: username,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
type: 'text',
|
|
||||||
parameter_name: 'code',
|
|
||||||
text: otpCode,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
type: 'text',
|
|
||||||
parameter_name: 'type',
|
|
||||||
text: type,
|
|
||||||
},
|
|
||||||
],
|
|
||||||
},
|
|
||||||
{
|
|
||||||
type: 'footer',
|
|
||||||
parameters: [
|
|
||||||
{
|
|
||||||
type: 'text',
|
|
||||||
text: 'Kode berlaku selama 5 menit.',
|
|
||||||
},
|
|
||||||
],
|
|
||||||
},
|
|
||||||
],
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
async requestOTP(payload: OtpRequestEntity, req: any) {
|
|
||||||
const otpService = new OtpService({ length: 4 });
|
|
||||||
const otpCode = otpService.generateSecureOTP();
|
|
||||||
const dateNow = this.generateTimestamp();
|
|
||||||
const expiredAt = this.generateOtpExpiration();
|
|
||||||
const userRequest = req?.user;
|
|
||||||
|
|
||||||
const newOtp: OtpVerificationEntity = {
|
|
||||||
otp_code: otpCode,
|
|
||||||
action_type: payload.action_type,
|
|
||||||
target_id: payload.target_id,
|
|
||||||
reference: payload.reference,
|
|
||||||
source: payload.source,
|
|
||||||
is_used: false,
|
|
||||||
is_replaced: false,
|
|
||||||
expired_at: expiredAt,
|
|
||||||
|
|
||||||
creator_id: userRequest?.id,
|
|
||||||
creator_name: userRequest?.name,
|
|
||||||
created_at: dateNow,
|
|
||||||
verified_at: null,
|
|
||||||
|
|
||||||
editor_id: userRequest?.id,
|
|
||||||
editor_name: userRequest?.name,
|
|
||||||
updated_at: dateNow,
|
|
||||||
};
|
|
||||||
|
|
||||||
const activeOTP = await this.getActiveOtp(
|
|
||||||
payload.target_id ? payload.target_id : payload.reference,
|
|
||||||
);
|
|
||||||
|
|
||||||
if (activeOTP) {
|
|
||||||
const createdAtMoment = moment(Number(activeOTP.created_at));
|
|
||||||
const nowMoment = moment(Number(dateNow));
|
|
||||||
const diffSeconds = nowMoment.diff(createdAtMoment, 'seconds');
|
|
||||||
const isProduction = process.env.NODE_ENV === 'true';
|
|
||||||
|
|
||||||
if (diffSeconds < 60 && isProduction) {
|
|
||||||
throw new BadRequestException(
|
|
||||||
'An active OTP request was made recently. Please try again later.',
|
|
||||||
);
|
|
||||||
} else {
|
|
||||||
// Update data is_replaced on database
|
|
||||||
this.otpVerificationRepo.save({
|
|
||||||
...activeOTP,
|
|
||||||
is_replaced: true,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// save otp to database
|
|
||||||
await this.otpVerificationRepo.save(newOtp);
|
|
||||||
const verifiers: OtpVerifierEntity[] = await this.getVerifier([
|
|
||||||
payload.action_type,
|
|
||||||
]);
|
|
||||||
const notificationService = new WhatsappService();
|
|
||||||
|
|
||||||
verifiers?.map((v) => {
|
|
||||||
notificationService.sendTemplateMessage({
|
|
||||||
phone: v.phone_number,
|
|
||||||
templateMsg: this.generateOTPMsgTemplate({ userRequest, newOtp }),
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
return {
|
|
||||||
message: `OTP has been sent to the admin's WhatsApp.`,
|
|
||||||
updated_at: expiredAt,
|
|
||||||
resend_available_at: this.generateResendAvailableAt(),
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
async verifyOTP(payload: OtpVerifyEntity, req: any) {
|
|
||||||
const userRequest = req?.user;
|
|
||||||
const { otp_code, action_type, target_id, reference, source } = payload;
|
|
||||||
const dateNow = this.generateTimestamp();
|
|
||||||
|
|
||||||
if (!target_id && !reference) {
|
|
||||||
throw new BadRequestException(
|
|
||||||
'Either target_id or reference must be provided.',
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
let otp: any;
|
|
||||||
|
|
||||||
// Build a where condition with OR between target_id and reference
|
|
||||||
|
|
||||||
if (target_id) {
|
|
||||||
otp = await this.otpVerificationRepo.findOne({
|
|
||||||
where: {
|
|
||||||
otp_code,
|
|
||||||
action_type,
|
|
||||||
target_id,
|
|
||||||
source,
|
|
||||||
is_used: false,
|
|
||||||
is_replaced: false,
|
|
||||||
},
|
|
||||||
});
|
|
||||||
} else if (reference) {
|
|
||||||
otp = await this.otpVerificationRepo.findOne({
|
|
||||||
where: {
|
|
||||||
otp_code,
|
|
||||||
action_type,
|
|
||||||
reference,
|
|
||||||
source,
|
|
||||||
is_used: false,
|
|
||||||
is_replaced: false,
|
|
||||||
},
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!otp) {
|
|
||||||
throw new BadRequestException('Invalid or expired OTP.');
|
|
||||||
} else if (otp.expired_at <= dateNow) {
|
|
||||||
throw new BadRequestException('OTP has expired.');
|
|
||||||
}
|
|
||||||
|
|
||||||
otp.is_used = true;
|
|
||||||
otp.verified_at = dateNow;
|
|
||||||
otp.editor_id = userRequest?.id;
|
|
||||||
otp.editor_name = userRequest?.name;
|
|
||||||
otp.updated_at = dateNow;
|
|
||||||
|
|
||||||
// update otp to database
|
|
||||||
await this.otpVerificationRepo.save(otp);
|
|
||||||
return { message: 'OTP verified successfully.' };
|
|
||||||
}
|
|
||||||
|
|
||||||
async getActiveOtp(payload: string) {
|
|
||||||
const now = this.generateTimestamp();
|
|
||||||
const tableName = TABLE_NAME.OTP_VERIFICATIONS;
|
|
||||||
|
|
||||||
return this.otpVerificationRepo
|
|
||||||
.createQueryBuilder(tableName)
|
|
||||||
.where(
|
|
||||||
`(${tableName}.target_id = :payload OR ${tableName}.reference = :payload)
|
|
||||||
AND ${tableName}.is_used = false
|
|
||||||
AND ${tableName}.is_replaced = false
|
|
||||||
AND ${tableName}.expired_at > :now`,
|
|
||||||
{ payload, now },
|
|
||||||
)
|
|
||||||
.orderBy(
|
|
||||||
`CASE WHEN ${tableName}.target_id = :payload THEN 0 ELSE 1 END`,
|
|
||||||
'ASC',
|
|
||||||
)
|
|
||||||
.getOne();
|
|
||||||
}
|
|
||||||
|
|
||||||
async getVerifier(actions: OTP_ACTION_TYPE[]) {
|
|
||||||
const tableALias = TABLE_NAME.OTP_VERIFIER;
|
|
||||||
const results = await this.otpVerifierRepo
|
|
||||||
.createQueryBuilder(tableALias)
|
|
||||||
.where(`${tableALias}.is_all_action = :isAll`, { isAll: true })
|
|
||||||
.orWhere(`${tableALias}.action_types && :actions`, { actions })
|
|
||||||
.getMany();
|
|
||||||
return results ?? [];
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -1,24 +0,0 @@
|
||||||
import { Injectable } from '@nestjs/common';
|
|
||||||
import { InjectRepository } from '@nestjs/typeorm';
|
|
||||||
import { Repository } from 'typeorm';
|
|
||||||
import { OtpVerifierModel } from '../models/otp-verifier.model';
|
|
||||||
import { OtpVerifierCreateDto } from '../../infrastructure/dto/otp-verification.dto';
|
|
||||||
import * as moment from 'moment';
|
|
||||||
|
|
||||||
@Injectable()
|
|
||||||
export class OtpVerifierService {
|
|
||||||
constructor(
|
|
||||||
@InjectRepository(OtpVerifierModel)
|
|
||||||
private readonly otpVerifierRepo: Repository<OtpVerifierModel>,
|
|
||||||
) {}
|
|
||||||
|
|
||||||
async create(payload: OtpVerifierCreateDto) {
|
|
||||||
const dateNow = moment().valueOf();
|
|
||||||
|
|
||||||
return this.otpVerifierRepo.save({
|
|
||||||
...payload,
|
|
||||||
created_at: dateNow,
|
|
||||||
updated_at: dateNow,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -1,50 +0,0 @@
|
||||||
import { BaseEntity } from 'src/core/modules/domain/entities//base.entity';
|
|
||||||
|
|
||||||
export enum OTP_ACTION_TYPE {
|
|
||||||
CREATE_DISCOUNT = 'CREATE_DISCOUNT',
|
|
||||||
CANCEL_TRANSACTION = 'CANCEL_TRANSACTION',
|
|
||||||
REJECT_RECONCILIATION = 'REJECT_RECONCILIATION',
|
|
||||||
|
|
||||||
ACTIVATE_USER = 'ACTIVATE_USER',
|
|
||||||
|
|
||||||
ACTIVATE_ITEM = 'ACTIVATE_ITEM',
|
|
||||||
UPDATE_ITEM_PRICE = 'UPDATE_ITEM_PRICE',
|
|
||||||
UPDATE_ITEM_DETAILS = 'UPDATE_ITEM_DETAILS',
|
|
||||||
|
|
||||||
CONFIRM_TRANSACTION = 'CONFIRM_TRANSACTION',
|
|
||||||
}
|
|
||||||
|
|
||||||
export enum OTP_SOURCE {
|
|
||||||
POS = 'POS',
|
|
||||||
WEB = 'WEB',
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface OtpVerificationEntity extends BaseEntity {
|
|
||||||
otp_code: string;
|
|
||||||
action_type: OTP_ACTION_TYPE;
|
|
||||||
target_id: string;
|
|
||||||
reference: string;
|
|
||||||
source: OTP_SOURCE;
|
|
||||||
is_used: boolean;
|
|
||||||
is_replaced: boolean;
|
|
||||||
expired_at: number;
|
|
||||||
verified_at: number;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface OtpRequestEntity {
|
|
||||||
action_type: OTP_ACTION_TYPE;
|
|
||||||
source: OTP_SOURCE;
|
|
||||||
target_id: string;
|
|
||||||
reference: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface OtpVerifyEntity extends OtpRequestEntity {
|
|
||||||
otp_code: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface OtpVerifierEntity {
|
|
||||||
name: string;
|
|
||||||
phone_number: string;
|
|
||||||
is_all_action?: boolean;
|
|
||||||
action_types?: OTP_ACTION_TYPE[] | null;
|
|
||||||
}
|
|
|
@ -1,112 +0,0 @@
|
||||||
import {
|
|
||||||
IsArray,
|
|
||||||
IsBoolean,
|
|
||||||
IsEnum,
|
|
||||||
IsNotEmpty,
|
|
||||||
IsOptional,
|
|
||||||
IsPhoneNumber,
|
|
||||||
IsString,
|
|
||||||
ValidateIf,
|
|
||||||
} from 'class-validator';
|
|
||||||
import {
|
|
||||||
OTP_ACTION_TYPE,
|
|
||||||
OTP_SOURCE,
|
|
||||||
OtpRequestEntity,
|
|
||||||
OtpVerifyEntity,
|
|
||||||
} from '../../domain/entities/otp-verification.entity';
|
|
||||||
import { ApiProperty } from '@nestjs/swagger';
|
|
||||||
import { Type } from 'class-transformer';
|
|
||||||
|
|
||||||
export class OtpRequestDto implements OtpRequestEntity {
|
|
||||||
@ApiProperty({
|
|
||||||
type: String,
|
|
||||||
required: true,
|
|
||||||
example: OTP_ACTION_TYPE.CANCEL_TRANSACTION,
|
|
||||||
description: 'CANCEL_TRANSACTION || CREATE_DISCOUNT',
|
|
||||||
})
|
|
||||||
@IsString()
|
|
||||||
@IsNotEmpty()
|
|
||||||
action_type: OTP_ACTION_TYPE;
|
|
||||||
|
|
||||||
@ApiProperty({
|
|
||||||
type: String,
|
|
||||||
required: true,
|
|
||||||
example: OTP_SOURCE.POS,
|
|
||||||
description: 'POS || WEB',
|
|
||||||
})
|
|
||||||
@IsString()
|
|
||||||
@IsNotEmpty()
|
|
||||||
source: OTP_SOURCE;
|
|
||||||
|
|
||||||
@ApiProperty({
|
|
||||||
name: 'target_id',
|
|
||||||
example: 'bccc0c6a-51a0-437f-abc8-dc18851604ee',
|
|
||||||
})
|
|
||||||
@IsString()
|
|
||||||
@ValidateIf((body) => body.target_id)
|
|
||||||
target_id: string;
|
|
||||||
|
|
||||||
@ApiProperty({ name: 'reference', example: '0625N21' })
|
|
||||||
@IsString()
|
|
||||||
@ValidateIf((body) => body.reference)
|
|
||||||
reference: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
export class OtpVerifyDto extends OtpRequestDto implements OtpVerifyEntity {
|
|
||||||
@ApiProperty({
|
|
||||||
name: 'otp_code',
|
|
||||||
type: String,
|
|
||||||
required: true,
|
|
||||||
example: '2345',
|
|
||||||
})
|
|
||||||
@IsString()
|
|
||||||
@IsNotEmpty()
|
|
||||||
otp_code: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
export class OtpVerifierCreateDto {
|
|
||||||
@ApiProperty({
|
|
||||||
example: 'Item Manager',
|
|
||||||
description: 'Nama verifier, opsional.',
|
|
||||||
})
|
|
||||||
@IsOptional()
|
|
||||||
@IsString()
|
|
||||||
name?: string;
|
|
||||||
|
|
||||||
@ApiProperty({
|
|
||||||
example: '6281234567890',
|
|
||||||
description: 'Nomor telepon verifier dalam format internasional (E.164).',
|
|
||||||
})
|
|
||||||
@IsString()
|
|
||||||
@IsPhoneNumber('ID')
|
|
||||||
phone_number: string;
|
|
||||||
|
|
||||||
@ApiProperty({
|
|
||||||
example: false,
|
|
||||||
description:
|
|
||||||
'True jika verifier boleh memverifikasi semua aksi tanpa batas.',
|
|
||||||
})
|
|
||||||
@IsBoolean()
|
|
||||||
is_all_action: boolean;
|
|
||||||
|
|
||||||
@ApiProperty({
|
|
||||||
isArray: true,
|
|
||||||
enum: OTP_ACTION_TYPE,
|
|
||||||
example: [
|
|
||||||
'CREATE_DISCOUNT',
|
|
||||||
'CANCEL_TRANSACTION',
|
|
||||||
'REJECT_RECONCILIATION',
|
|
||||||
'ACTIVATE_ITEM',
|
|
||||||
'ACTIVATE_USER',
|
|
||||||
'UPDATE_ITEM_PRICE',
|
|
||||||
'UPDATE_ITEM_DETAILS',
|
|
||||||
'CONFIRM_TRANSACTION',
|
|
||||||
],
|
|
||||||
description: 'Daftar tipe aksi yang boleh diverifikasi, jika bukan semua.',
|
|
||||||
})
|
|
||||||
@IsOptional()
|
|
||||||
@IsArray()
|
|
||||||
@IsEnum(OTP_ACTION_TYPE, { each: true })
|
|
||||||
@Type(() => String)
|
|
||||||
action_types?: OTP_ACTION_TYPE[];
|
|
||||||
}
|
|
|
@ -1,82 +0,0 @@
|
||||||
// auth/otp-auth.guard.ts
|
|
||||||
import {
|
|
||||||
CanActivate,
|
|
||||||
ExecutionContext,
|
|
||||||
Injectable,
|
|
||||||
UnprocessableEntityException,
|
|
||||||
} from '@nestjs/common';
|
|
||||||
import { JwtService } from '@nestjs/jwt';
|
|
||||||
import { InjectDataSource } from '@nestjs/typeorm';
|
|
||||||
import { validatePassword } from 'src/core/helpers/password/bcrypt.helpers';
|
|
||||||
import {
|
|
||||||
CONNECTION_NAME,
|
|
||||||
STATUS,
|
|
||||||
} from 'src/core/strings/constants/base.constants';
|
|
||||||
import { UserRole } from 'src/modules/user-related/user/constants';
|
|
||||||
import { UserModel } from 'src/modules/user-related/user/data/models/user.model';
|
|
||||||
import { DataSource, Not } from 'typeorm';
|
|
||||||
|
|
||||||
@Injectable()
|
|
||||||
export class OtpAuthGuard implements CanActivate {
|
|
||||||
constructor(
|
|
||||||
private readonly jwtService: JwtService,
|
|
||||||
|
|
||||||
@InjectDataSource(CONNECTION_NAME.DEFAULT)
|
|
||||||
protected readonly dataSource: DataSource,
|
|
||||||
) {}
|
|
||||||
|
|
||||||
get userRepository() {
|
|
||||||
return this.dataSource.getRepository(UserModel);
|
|
||||||
}
|
|
||||||
|
|
||||||
async canActivate(context: ExecutionContext): Promise<boolean> {
|
|
||||||
const request = context.switchToHttp().getRequest();
|
|
||||||
const jwtAuth = request.headers['authorization'];
|
|
||||||
const basicAuth = request.headers['x-basic-authorization'];
|
|
||||||
|
|
||||||
// 1. Cek OTP Auth (basic_authorization header)
|
|
||||||
if (basicAuth) {
|
|
||||||
try {
|
|
||||||
const decoded = Buffer.from(basicAuth, 'base64').toString('ascii');
|
|
||||||
const [username, password] = decoded.split('|');
|
|
||||||
|
|
||||||
const userLogin = await this.userRepository.findOne({
|
|
||||||
where: {
|
|
||||||
username: username,
|
|
||||||
status: STATUS.ACTIVE,
|
|
||||||
role: Not(UserRole.QUEUE_ADMIN),
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
const valid = await validatePassword(password, userLogin?.password);
|
|
||||||
|
|
||||||
if (userLogin && valid) {
|
|
||||||
request.user = userLogin;
|
|
||||||
return true;
|
|
||||||
} else {
|
|
||||||
throw new UnprocessableEntityException(
|
|
||||||
'Invalid username or password.',
|
|
||||||
);
|
|
||||||
}
|
|
||||||
} catch (err) {
|
|
||||||
throw new UnprocessableEntityException('Invalid username or password.');
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// 2. Cek JWT (Authorization: Bearer <token>)
|
|
||||||
if (jwtAuth && jwtAuth.startsWith('Bearer ')) {
|
|
||||||
const token = jwtAuth.split(' ')[1];
|
|
||||||
try {
|
|
||||||
const payload = await this.jwtService.verifyAsync(token);
|
|
||||||
request.user = payload;
|
|
||||||
return true;
|
|
||||||
} catch (err) {
|
|
||||||
throw new UnprocessableEntityException('Invalid JWT token');
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
throw new UnprocessableEntityException(
|
|
||||||
'No valid authentication method found',
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue