Compare commits

...

106 Commits

Author SHA1 Message Date
shancheas b96d24de1a feat: add query filter for active booking items in BookingItemManager 2025-06-24 12:44:00 +07:00
shancheas 5d3f9d7bff fix(SPG-1254): ONLINE BOOKING wahana tenant tidak muncul pada catalog online booking 2025-06-24 11:51:43 +07:00
shancheas 831593e743 Merge branch 'development' of ssh://git.eigen.co.id:2222/eigen/pos-be into development 2025-06-20 14:48:55 +07:00
shancheas 162bd0918f fix: ensure safe access to season period IDs in booking item pricing logic 2025-06-20 14:48:45 +07:00
firmanr 13b5838393 Merge pull request 'feat(SPG-1137): add time group at booking and refund detail' (#161) from feat/otp-cancel into development
Reviewed-on: #161
2025-06-19 18:43:57 +07:00
Firman Ramdhani 63bb55b04b feat(SPG-1137): add time group at booking and refund detail 2025-06-19 18:30:07 +07:00
firmanr 9d1c240b6b Merge pull request 'feat(SPG-1236): setup otp checker guard' (#160) from feat/otp-cancel into development
Reviewed-on: #160
2025-06-19 17:10:07 +07:00
Firman Ramdhani 83f3377465 feat(SPG-1236): setup otp checker guard 2025-06-19 17:09:42 +07:00
firmanr 69c2ee06cf Merge pull request 'feat(SPG-1236): implement otp checker guard on session period' (#159) from feat/otp-cancel into development
Reviewed-on: #159
2025-06-19 17:04:51 +07:00
Firman Ramdhani 42060384aa feat(SPG-1236): implement otp checker guard on session period 2025-06-19 17:04:07 +07:00
firmanr 62cfb1f1a8 Merge pull request 'feat/otp-cancel' (#158) from feat/otp-cancel into development
Reviewed-on: #158
2025-06-19 16:36:52 +07:00
Firman Ramdhani 08a35dfdf4 feat(SPG-1236): implement otp checker guard on booking transaction 2025-06-19 16:32:48 +07:00
Firman Ramdhani 8df836ff3e feat(SPG-1236): implement otp checker guard on session period 2025-06-19 16:24:20 +07:00
Firman Ramdhani 822cfe606a feat(SPG-1236): implement otp checker guard on active and confirm user 2025-06-19 15:55:19 +07:00
Firman Ramdhani de43f0f28b feat(SPG-1236): setup otp checker guard 2025-06-19 15:55:01 +07:00
shancheas 09b0133bf4 fix: update booking item pricing logic to use current rate based on season period IDs 2025-06-19 15:34:12 +07:00
shancheas a77e6b0381 feat: add usage_type field to items and item_queues with corresponding database migration 2025-06-19 14:49:09 +07:00
shancheas a5da557dd9 feat: implement booking expired notification in WhatsApp service 2025-06-19 14:40:17 +07:00
shancheas afad02ba52 fix: temporarily disable OtpAuthGuard in saveToCouch method for transaction data controller 2025-06-17 15:03:17 +07:00
shancheas 6636c596f4 Merge branch 'development' of ssh://git.eigen.co.id:2222/eigen/pos-be into development 2025-06-17 14:26:50 +07:00
shancheas 01fb358875 feat: enhance transaction read service to include total sales calculation and item ID in quantity query 2025-06-17 14:26:40 +07:00
firmanr f9dc49f7d5 Merge pull request 'feat/otp-cancel' (#157) from feat/otp-cancel into development
Reviewed-on: #157
2025-06-17 09:10:29 +07:00
Firman Ramdhani 1d9cdfe8e6 feat(SPG-1234): add action_type at verifier 2025-06-16 12:20:47 +07:00
Firman Ramdhani ccc363f74f feat(SPG-1234): add action_type at verifier 2025-06-16 12:15:20 +07:00
Firman Ramdhani af1ee2fbee feat(SPG-1234): add action_type at verifier 2025-06-16 12:11:24 +07:00
Firman Ramdhani ec5229645f feat(SPG-1234): add action_type at verifier 2025-06-16 11:48:56 +07:00
shancheas 47d45cb65c feat: integrate CouchDB module across various services and add transaction summary endpoint 2025-06-16 11:27:12 +07:00
shancheas d6717c9c60 feat: add resend notification endpoint in BookingOrderController to send WhatsApp notifications 2025-06-16 09:26:09 +07:00
shancheas d995982203 Merge branch 'development' of ssh://git.eigen.co.id:2222/eigen/pos-be into development 2025-06-11 19:03:26 +07:00
shancheas 56e475d61f fix: ensure time_group data is only accessed if it exists in BookingOrderController 2025-06-11 19:03:09 +07:00
shancheas 3116acd5ab feat: add image_url to booking item selection in BookingItemManager 2025-06-11 19:02:10 +07:00
firmanr 068c4ce349 Merge pull request 'feat: rename header key basic auth' (#156) from feat/otp-cancel into development
Reviewed-on: #156
2025-06-11 18:28:47 +07:00
Firman Ramdhani 79c9139c3c feat: rename header key basic auth 2025-06-11 18:28:21 +07:00
firmanr d4e8e72af0 Merge pull request 'feat: rename header key basic auth' (#155) from feat/otp-cancel into development
Reviewed-on: #155
2025-06-11 18:15:45 +07:00
Firman Ramdhani 7dd29c2a70 feat: rename header key basic auth 2025-06-11 18:15:09 +07:00
firmanr 0b5b0ce09b Merge pull request 'feat: update validation otp cancel reconciliation' (#154) from feat/otp-cancel into development
Reviewed-on: #154
2025-06-11 17:53:15 +07:00
Firman Ramdhani e1d3ee7188 feat: update validation otp cancel reconciliation 2025-06-11 17:52:18 +07:00
shancheas 838670c822 Merge branch 'development' of ssh://git.eigen.co.id:2222/eigen/pos-be into development 2025-06-11 16:31:28 +07:00
shancheas 34d8882ec3 feat: make update price public 2025-06-11 16:31:15 +07:00
firmanr 8fb8aac0f9 Merge pull request 'feat: update validation otp cancel reconciliation' (#153) from feat/otp-cancel into development
Reviewed-on: #153
2025-06-11 16:00:02 +07:00
Firman Ramdhani 3a0efb00a9 feat: update validation otp cancel reconciliation 2025-06-11 15:55:21 +07:00
shancheas 737575176e Merge branch 'development' of ssh://git.eigen.co.id:2222/eigen/pos-be into development 2025-06-11 15:46:53 +07:00
shancheas f0e8fbddc9 feat: include parent transaction details in booking order retrieval 2025-06-11 15:46:43 +07:00
shancheas d8fa72ba20 feat: implement BookingItemManager for enhanced item booking functionality 2025-06-11 15:41:07 +07:00
firmanr ab9db39a5f Merge pull request 'feat: add feature basic auth request OTP' (#152) from feat/otp-cancel into development
Reviewed-on: #152
2025-06-11 14:58:12 +07:00
Firman Ramdhani 7c45a20866 feat: add feature basic auth request OTP 2025-06-11 14:56:43 +07:00
shancheas 7ff0040f9e refactor: enhance time group data structure in booking order controller 2025-06-11 13:04:32 +07:00
shancheas 9bbd37ba38 refactor: update time group handling in booking order controller 2025-06-11 13:03:48 +07:00
shancheas b476c92b70 feat: add time group information to detail booking 2025-06-11 11:04:41 +07:00
shancheas dc926d84e4 refactor: streamline rescheduling logic and enhance transaction retrieval
- Replaced direct transaction retrieval with a dedicated method for better clarity.
- Consolidated validation checks for rescheduling into the controller.
- Added booking date to the transaction data being created.
- Improved error handling for various transaction states during rescheduling.
2025-06-11 10:35:06 +07:00
shancheas 0172eea573 Merge branch 'development' of ssh://git.eigen.co.id:2222/eigen/pos-be into development 2025-06-11 08:53:25 +07:00
shancheas 464f5cb49e feat: add booking parent relationship to transactions and implement rescheduling functionality 2025-06-11 08:53:12 +07:00
firmanr 1e395ae53f Merge pull request 'feat: sync time group to couch' (#151) from feat/otp-cancel into development
Reviewed-on: #151
2025-06-10 16:45:26 +07:00
Firman Ramdhani 2f2fc27965 feat: sync time group to couch 2025-06-10 16:44:58 +07:00
irfan 0512c51f8e Merge pull request 'feat: sync time group to couch' (#150) from feat/otp-cancel into development
Reviewed-on: #150
2025-06-10 16:42:59 +07:00
Firman Ramdhani 6da2118ab5 feat: sync time group to couch 2025-06-10 16:38:06 +07:00
shancheas 033ed0046e Merge branch 'development' of ssh://git.eigen.co.id:2222/eigen/pos-be into development 2025-06-10 16:34:17 +07:00
shancheas fdbd667b7d feat: enhance loginQueue method to filter orders by date range 2025-06-10 16:34:00 +07:00
shancheas baeb72fe7d feat: add filtering option for items based on time group presence 2025-06-10 16:33:36 +07:00
firmanr 4e2ec4d94f Merge pull request 'feat: save otp code when reject reconciliation' (#149) from feat/otp-cancel into development
Reviewed-on: #149
2025-06-10 16:16:07 +07:00
Firman Ramdhani 94fbec0c78 feat: save otp code when reject reconciliation 2025-06-10 16:02:05 +07:00
firmanr e24fee86ba Merge pull request 'feat/otp-cancel' (#148) from feat/otp-cancel into development
Reviewed-on: #148
2025-06-10 15:19:45 +07:00
Firman Ramdhani 16df6945b7 feat: fix validation generate otp 2025-06-10 15:17:35 +07:00
Firman Ramdhani 8497a5779d feat: fix validation generate otp 2025-06-10 15:02:43 +07:00
shancheas 399ca0bdda Merge branch 'development' of ssh://git.eigen.co.id:2222/eigen/pos-be into development 2025-06-10 14:31:07 +07:00
shancheas b8dd2a4e01 temp: update WhatsApp notification method for rescheduling to use OTP notification 2025-06-10 14:30:50 +07:00
shancheas 6a7ab72e12 feat: add booking description field to item model and database 2025-06-10 14:29:46 +07:00
shancheas ffc75ba174 feat: integrate WhatsApp notifications for booking registration and rescheduling 2025-06-10 13:28:58 +07:00
firmanr 18afc47030 Merge pull request 'feat/otp-cancel' (#147) from feat/otp-cancel into development
Reviewed-on: #147
2025-06-10 13:21:34 +07:00
Firman Ramdhani dc1fadbe1f Merge branch 'development' of ssh://git.eigen.co.id:2222/eigen/pos-be into feat/otp-cancel 2025-06-10 13:21:06 +07:00
Firman Ramdhani a1ed81eec5 feat: change length otp checker 2025-06-10 13:20:53 +07:00
shancheas 8192396085 feat: implement reschedule verification process with OTP functionality 2025-06-10 10:26:36 +07:00
shancheas 3661d9d171 feat: increase item limit to 1000 and enhance query for time group filtering 2025-06-09 17:26:57 +07:00
shancheas d4d605d168 feat: add whatsapp notification for booking created 2025-06-09 16:55:55 +07:00
shancheas 10a553ac9d Merge branch 'development' of ssh://git.eigen.co.id:2222/eigen/pos-be into development 2025-06-09 10:11:36 +07:00
shancheas d95f8fd6e5 feat: add time_group_ids filter to item management and DTO 2025-06-09 10:11:16 +07:00
firmanr 9bc2f5fde2 Merge pull request 'feat/otp-cancel' (#146) from feat/otp-cancel into development
Reviewed-on: #146
2025-06-05 17:11:14 +07:00
Firman Ramdhani 0d8ec858eb feat: add api get time group items public 2025-06-05 17:10:33 +07:00
Firman Ramdhani c97399ae8f feat: add api get time group items public 2025-06-05 17:08:39 +07:00
firmanr 5b7df0e372 Merge pull request 'feat: update validation otp' (#145) from feat/otp-cancel into development
Reviewed-on: #145
2025-06-05 16:46:45 +07:00
Firman Ramdhani ca886069f1 feat: update validation otp 2025-06-05 16:45:58 +07:00
firmanr 73c87f6819 Merge pull request 'feat/otp-cancel' (#144) from feat/otp-cancel into development
Reviewed-on: #144
2025-06-05 14:32:34 +07:00
Firman Ramdhani d86f4075d4 feat: rename label kode otp at giving discount report 2025-06-05 12:40:13 +07:00
Firman Ramdhani 88753546b6 feat: add otp column at report, cancel transaction, giving discount, reconciliation, vip_code 2025-06-05 12:12:31 +07:00
Firman Ramdhani cc78dfbd06 feat: monitor log data mapper create discount 2025-06-05 10:17:06 +07:00
Firman Ramdhani f9025faf0b feat: setup message 2025-06-04 22:22:14 +07:00
Firman Ramdhani 6a0b1f6e05 feat: setup verifier 2025-06-04 21:27:34 +07:00
Firman Ramdhani 67129a8c69 Merge branch 'development' of ssh://git.eigen.co.id:2222/eigen/pos-be into feat/otp-cancel 2025-06-04 20:18:06 +07:00
Firman Ramdhani 798476aaf5 feat: implement module otp verification 2025-06-04 20:15:24 +07:00
Firman Ramdhani ee52a35af2 feat: implement module otp verification 2025-06-04 20:08:55 +07:00
Firman Ramdhani 538abb122f feat: implement module otp verification 2025-06-04 20:01:23 +07:00
shancheas 36b6ee733f feat: add OTP whatsapp notification 2025-06-04 15:32:05 +07:00
Firman Ramdhani d8cfa97612 fix: add time group at item bundling 2025-06-04 14:41:46 +07:00
Firman Ramdhani 5f08b4be66 feat: setup module otp verifications 2025-06-04 09:48:10 +07:00
Firman Ramdhani 5e328fda1e feat: fix response time group 2025-06-03 15:27:30 +07:00
Firman Ramdhani ffd8595ab2 feat: add column top_code 2025-06-03 14:26:09 +07:00
shancheas 63e43a7ba0 fix: change midtrans id to uuid 2025-06-02 15:33:22 +07:00
shancheas bc8a0407a6 feat: check booking status by id 2025-06-02 14:03:58 +07:00
irfan 9a3d544699 Merge pull request 'feat/SPG-1128-time-group' (#143) from feat/SPG-1128-time-group into development
Reviewed-on: #143
2025-06-02 13:47:45 +07:00
Firman Ramdhani 845e0547ab feat(SPG-1133): penambahan kolom dan filter time group di report income per item dan report income per item master 2025-05-28 18:26:52 +07:00
Firman Ramdhani 9e5d59baac feat: add table relation at event handler item 2025-05-28 17:13:13 +07:00
Firman Ramdhani 89dc1fc160 feat: add relation time group at handle update item 2025-05-28 17:04:26 +07:00
Firman Ramdhani 16bbb1f02b feat(SPG-1140): menambahkan validasi end time untuk create dan update time group 2025-05-28 16:00:58 +07:00
Firman Ramdhani 339b2bdab6 feat: menambahkan validasi end time untuk create dan update time group 2025-05-28 15:48:36 +07:00
Firman Ramdhani a80e2e3419 feat: memasangkan time group di item rate, item, dan item antrian 2025-05-28 15:08:38 +07:00
Firman Ramdhani 3b362d2822 feat: crete API CRUD feature time group 2025-05-28 14:52:26 +07:00
123 changed files with 4096 additions and 56 deletions

View File

@ -59,6 +59,7 @@
"pdfmake": "^0.2.10",
"pg": "^8.11.5",
"plop": "^4.0.1",
"qrcode": "^1.5.4",
"reflect-metadata": "^0.2.0",
"rxjs": "^7.5.0",
"typeorm": "^0.3.20",
@ -71,6 +72,7 @@
"@types/express": "^4.17.13",
"@types/jest": "29.5.12",
"@types/node": "^20.12.13",
"@types/qrcode": "^1.5.5",
"@types/supertest": "^2.0.11",
"@typescript-eslint/eslint-plugin": "^5.0.0",
"@typescript-eslint/parser": "^5.0.0",

View File

@ -99,6 +99,15 @@ 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';
@Module({
imports: [
ApmModule.register(),
@ -123,6 +132,7 @@ import { BookingOrderModule } from './modules/booking-online/order/order.module'
ItemCategoryModel,
ItemRateModel,
ItemQueueModel,
TimeGroupModel,
LogModel,
LogUserLoginModel,
NewsModel,
@ -162,6 +172,10 @@ import { BookingOrderModule } from './modules/booking-online/order/order.module'
// Booking Online
VerificationModel,
RescheduleVerificationModel,
OtpVerificationModel,
OtpVerifierModel,
],
synchronize: false,
}),
@ -188,6 +202,7 @@ import { BookingOrderModule } from './modules/booking-online/order/order.module'
ItemModule,
ItemRateModule,
ItemQueueModule,
TimeGroupModule,
// transaction
PaymentMethodModule,
@ -226,11 +241,14 @@ import { BookingOrderModule } from './modules/booking-online/order/order.module'
BookingOnlineAuthModule,
BookingOrderModule,
OtpVerificationModule,
],
controllers: [],
providers: [
AuthService,
PrivilegeService,
OtpCheckerGuard,
/**
* By default all request from client will protect by JWT
* if there is some endpoint/function that does'nt require authentication

View File

@ -0,0 +1,57 @@
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.');
}
}

View File

@ -0,0 +1,66 @@
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;
}
}

View File

@ -28,4 +28,9 @@ export enum MODULE_NAME {
REPORT_SUMMARY = 'report-summary',
QUEUE = 'queue',
TIME_GROUPS = 'time-groups',
OTP_VERIFICATIONS = 'otp-verification',
OTP_VERIFIER = 'otp-verifier',
}

View File

@ -43,4 +43,8 @@ export enum TABLE_NAME {
QUEUE_TICKET = 'queue_tickets',
QUEUE_ITEM = 'queue_items',
QUEUE_BUCKET = 'queue_bucket',
TIME_GROUPS = 'time_groups',
OTP_VERIFICATIONS = 'otp_verifications',
OTP_VERIFIER = 'otp_verifier',
}

View File

@ -0,0 +1,27 @@
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"`);
}
}

View File

@ -0,0 +1,21 @@
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"`);
}
}

View File

@ -0,0 +1,29 @@
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"`,
);
}
}

View File

@ -0,0 +1,19 @@
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"`,
);
}
}

View File

@ -0,0 +1,15 @@
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"`);
}
}

View File

@ -0,0 +1,37 @@
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"`,
);
}
}

View File

@ -0,0 +1,28 @@
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"`);
}
}

View File

@ -0,0 +1,19 @@
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"`,
);
}
}

View File

@ -0,0 +1,24 @@
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"`,
);
}
}

View File

@ -0,0 +1,55 @@
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"`,
);
}
}

View File

@ -0,0 +1,29 @@
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"`);
}
}

View File

@ -4,6 +4,7 @@ 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)
@ -24,22 +25,28 @@ export class VerificationService {
}
async register(data: BookingVerification) {
const isProduction = process.env.NODE_ENV === 'true';
const currentTime = Math.floor(Date.now()); // current time in seconds
if (
data.created_at &&
currentTime - data.created_at > this.expiredTimeRegister
) {
throw new UnprocessableEntityException('Please try again in 1 minute');
}
// Generate a 4 digit OTP code
data.code = Math.floor(1000 + Math.random() * 9000).toString();
data.tried = 0;
data.updated_at = currentTime;
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);
@ -47,7 +54,15 @@ export class VerificationService {
// Create new record
verification = this.verificationRepository.create(data);
}
return this.verificationRepository.save(verification);
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) {

View File

@ -0,0 +1,9 @@
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;
}

View File

@ -0,0 +1,36 @@
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;
}

View File

@ -0,0 +1,16 @@
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;
}

View File

@ -0,0 +1,67 @@
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;
}
}

View File

@ -5,11 +5,14 @@ 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',
@ -18,7 +21,7 @@ export class CreateBookingManager extends CreateTransactionManager {
try {
const { token, redirect_url } = await this.dataServiceFirstOpt.create({
...this.data,
id: invoiceCode,
id,
});
Object.assign(this.data, {
payment_midtrans_token: token,
@ -34,10 +37,27 @@ export class CreateBookingManager extends CreateTransactionManager {
}
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,
},
`snap/v4/redirection/${this.data.payment_midtrans_token}`,
);
}
}

View File

@ -0,0 +1,115 @@
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;
}
}

View File

@ -0,0 +1,90 @@
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,
};
}
}

View File

@ -0,0 +1,47 @@
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;
}

View File

@ -1,19 +1,19 @@
import { Controller, Get, Query } from '@nestjs/common';
import { ApiBearerAuth, ApiTags } from '@nestjs/swagger';
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 { IndexItemManager } from 'src/modules/item-related/item/domain/usecases/managers/index-item.manager';
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: IndexItemManager,
private indexManager: BookingItemManager,
private serviceData: ItemReadService,
) {}
@ -21,7 +21,9 @@ export class ItemController {
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();

View File

@ -1,13 +1,32 @@
import { Body, Controller, Post } from '@nestjs/common';
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 { TransactionType } from 'src/modules/transaction/transaction/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')
@ -17,6 +36,8 @@ export class BookingOrderController {
private createBooking: CreateBookingManager,
private serviceData: TransactionDataService,
private midtransService: MidtransService,
private rescheduleVerification: RescheduleVerificationManager,
private rescheduleManager: RescheduleManager,
) {}
@Post()
@ -36,13 +57,218 @@ export class BookingOrderController {
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',
});
}
}
}

View File

@ -11,16 +11,28 @@ 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], CONNECTION_NAME.DEFAULT),
TypeOrmModule.forFeature(
[ItemModel, RescheduleVerificationModel],
CONNECTION_NAME.DEFAULT,
),
ItemModule,
TransactionModule,
MidtransModule,
CqrsModule,
],
controllers: [ItemController, BookingOrderController],
providers: [CreateBookingManager],
providers: [
CreateBookingManager,
RescheduleVerificationManager,
RescheduleManager,
BookingItemManager,
],
})
export class BookingOrderModule {}

View File

@ -3,4 +3,5 @@ export const DatabaseListen = [
'vip_code',
'pos_activity',
'pos_cash_activity',
'time_groups',
];

View File

@ -52,6 +52,10 @@ import { SeasonPeriodDataService } from 'src/modules/season-related/season-perio
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 { UserLoginModel } from 'src/modules/user-related/user/data/models/user-login.model';
import {
TimeGroupDeletedHandler,
TimeGroupUpdatedHandler,
} from './domain/managers/time-group.handle';
@Module({
imports: [
@ -83,6 +87,10 @@ import { UserLoginModel } from 'src/modules/user-related/user/data/models/user-l
VipCodeCreatedHandler,
VipCategoryDeletedHandler,
VipCategoryUpdatedHandler,
TimeGroupDeletedHandler,
TimeGroupUpdatedHandler,
SeasonPeriodDeletedHandler,
SeasonPeriodUpdatedHandler,
ItemUpdatedHandler,

View File

@ -44,10 +44,12 @@ export class ItemUpdatedHandler
'item_category',
'bundling_items',
'bundling_items.item_category',
'bundling_items.time_group',
'item_rates',
'item_rates.item',
'item_rates.season_period',
'item_rates.season_period.season_type',
'time_group',
],
});
@ -105,10 +107,12 @@ export class ItemPriceUpdatedHandler
'item_category',
'bundling_items',
'bundling_items.item_category',
'bundling_items.time_group',
'item_rates',
'item_rates.item',
'item_rates.season_period',
'item_rates.season_period.season_type',
'time_group',
],
});
@ -146,10 +150,12 @@ export class ItemRateUpdatedHandler
'item_category',
'bundling_items',
'bundling_items.item_category',
'bundling_items.time_group',
'item_rates',
'item_rates.item',
'item_rates.season_period',
'item_rates.season_period.season_type',
'time_group',
],
});

View File

@ -0,0 +1,65 @@
import { EventsHandler, IEventHandler } from '@nestjs/cqrs';
import { CouchService } from '../../data/services/couch.service';
import { STATUS } from 'src/core/strings/constants/base.constants';
import { 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',
);
}
}
}

View File

@ -10,7 +10,7 @@ import { TypeOrmModule } from '@nestjs/typeorm';
import { CONNECTION_NAME } from 'src/core/strings/constants/base.constants';
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 { CouchModule } from 'src/modules/configuration/couch/couch.module';
@Module({
imports: [
ConfigModule.forRoot(),
@ -19,6 +19,7 @@ import { TransactionTaxModel } from 'src/modules/transaction/transaction/data/mo
CONNECTION_NAME.DEFAULT,
),
CqrsModule,
CouchModule,
],
controllers: [GoogleCalendarController],
providers: [

View File

@ -10,7 +10,7 @@ import { TransactionDataService } from 'src/modules/transaction/transaction/data
import { PaymentTransactionHandler } from './domain/handlers/payment-transaction.handler';
import { MailTemplateController } from './infrastructure/mail.controller';
import { PdfMakeManager } from '../export/domain/managers/pdf-make.manager';
import { CouchModule } from '../couch/couch.module';
@Module({
imports: [
ConfigModule.forRoot(),
@ -19,6 +19,7 @@ import { PdfMakeManager } from '../export/domain/managers/pdf-make.manager';
CONNECTION_NAME.DEFAULT,
),
CqrsModule,
CouchModule,
],
controllers: [MailTemplateController],
providers: [

View File

@ -0,0 +1,41 @@
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
}

View File

@ -0,0 +1,25 @@
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;
}

View File

@ -0,0 +1,266 @@
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 ?? [];
}
}

View File

@ -0,0 +1,24 @@
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,
});
}
}

View File

@ -0,0 +1,50 @@
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;
}

View File

@ -0,0 +1,112 @@
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[];
}

View File

@ -0,0 +1,80 @@
// 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 OTP credentials');
}
} catch (err) {
throw new UnprocessableEntityException('Invalid OTP encoding');
}
}
// 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',
);
}
}

View File

@ -0,0 +1,60 @@
import {
Body,
Controller,
Get,
Param,
Post,
Req,
UseGuards,
} from '@nestjs/common';
import { ApiBearerAuth, ApiTags } from '@nestjs/swagger';
import { ExcludePrivilege, Public } from 'src/core/guards';
import { MODULE_NAME } from 'src/core/strings/constants/module.constants';
import { OtpVerificationService } from '../data/services/otp-verification.service';
import {
OtpRequestDto,
OtpVerifierCreateDto,
OtpVerifyDto,
} from './dto/otp-verification.dto';
import { OtpAuthGuard } from './guards/otp-auth.guard';
import { OtpVerifierService } from '../data/services/otp-verifier.service';
@ApiTags(`${MODULE_NAME.OTP_VERIFICATIONS.split('-').join(' ')} - data`)
@Controller(`v1/${MODULE_NAME.OTP_VERIFICATIONS}`)
@Public()
export class OtpVerificationController {
constructor(
private readonly otpVerificationService: OtpVerificationService,
) {}
@Post('request')
@UseGuards(OtpAuthGuard)
async request(@Body() body: OtpRequestDto, @Req() req) {
return await this.otpVerificationService.requestOTP(body, req);
}
@Post('verify')
@UseGuards(OtpAuthGuard)
async verify(@Body() body: OtpVerifyDto, @Req() req) {
return await this.otpVerificationService.verifyOTP(body, req);
}
@Get(':ref_or_target_id')
async getByPhoneNumber(@Param('ref_or_target_id') ref_or_target_id: string) {
return this.otpVerificationService.getActiveOtp(ref_or_target_id);
}
}
@ApiTags(`${MODULE_NAME.OTP_VERIFIER.split('-').join(' ')} - data`)
@Controller(`v1/${MODULE_NAME.OTP_VERIFIER}`)
@ApiBearerAuth('JWT')
@Public(false)
export class OtpVerifierController {
constructor(private readonly otpVerifierService: OtpVerifierService) {}
@Post()
@ExcludePrivilege()
async create(@Body() body: OtpVerifierCreateDto) {
return await this.otpVerifierService.create(body);
}
}

View File

@ -0,0 +1,37 @@
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 { OtpVerificationModel } from './data/models/otp-verification.model';
import {
OtpVerificationController,
OtpVerifierController,
} from './infrastructure/otp-verification-data.controller';
import { OtpVerificationService } from './data/services/otp-verification.service';
import { OtpVerifierModel } from './data/models/otp-verifier.model';
import { OtpAuthGuard } from './infrastructure/guards/otp-auth.guard';
import { JwtModule } from '@nestjs/jwt';
import { JWT_EXPIRED } from 'src/core/sessions/constants';
import { JWT_SECRET } from 'src/core/sessions/constants';
import { OtpVerifierService } from './data/services/otp-verifier.service';
@Module({
imports: [
ConfigModule.forRoot(),
TypeOrmModule.forFeature(
[OtpVerificationModel, OtpVerifierModel],
CONNECTION_NAME.DEFAULT,
),
JwtModule.register({
secret: JWT_SECRET,
signOptions: { expiresIn: JWT_EXPIRED },
}),
],
controllers: [OtpVerificationController, OtpVerifierController],
providers: [OtpAuthGuard, OtpVerificationService, OtpVerifierService],
})
export class OtpVerificationModule {}

View File

@ -5,3 +5,8 @@ export enum ItemType {
FREE_GIFT = 'free gift',
OTHER = 'other',
}
export enum UsageType {
ONE_TIME = 'one_time',
MULTIPLE = 'multiple',
}

View File

@ -2,7 +2,7 @@ import { TABLE_NAME } from 'src/core/strings/constants/table.constants';
import { ItemQueueEntity } from '../../domain/entities/item-queue.entity';
import { Column, Entity, OneToMany } from 'typeorm';
import { BaseStatusModel } from 'src/core/modules/data/model/base-status.model';
import { ItemType } from '../../constants';
import { ItemType, UsageType } from '../../constants';
import { ItemModel } from 'src/modules/item-related/item/data/models/item.model';
@Entity(TABLE_NAME.ITEM_QUEUE)
@ -29,6 +29,13 @@ export class ItemQueueModel
})
item_type: ItemType;
@Column('enum', {
name: 'usage_type',
enum: UsageType,
default: UsageType.ONE_TIME,
})
usage_type: UsageType;
@OneToMany(() => ItemModel, (model) => model.item_queue, {
onUpdate: 'CASCADE',
})

View File

@ -1,5 +1,5 @@
import { BaseStatusEntity } from 'src/core/modules/domain/entities/base-status.entity';
import { ItemType } from '../../constants';
import { ItemType, UsageType } from '../../constants';
import { ItemEntity } from 'src/modules/item-related/item/domain/entities/item.entity';
export interface ItemQueueEntity extends BaseStatusEntity {
@ -11,4 +11,5 @@ export interface ItemQueueEntity extends BaseStatusEntity {
items: ItemEntity[];
use_notification?: boolean;
requiring_notification?: boolean;
usage_type?: UsageType;
}

View File

@ -20,7 +20,7 @@ export class DetailItemQueueManager extends BaseDetailManager<ItemQueueEntity> {
get relations(): RelationParam {
return {
joinRelations: [],
selectRelations: ['items'],
selectRelations: ['items', 'items.time_group'],
countRelations: [],
};
}
@ -40,6 +40,7 @@ export class DetailItemQueueManager extends BaseDetailManager<ItemQueueEntity> {
`${this.tableName}.call_preparation`,
`${this.tableName}.use_notification`,
`${this.tableName}.requiring_notification`,
`${this.tableName}.usage_type`,
`items.id`,
`items.created_at`,
@ -53,6 +54,9 @@ export class DetailItemQueueManager extends BaseDetailManager<ItemQueueEntity> {
`items.share_profit`,
`items.play_estimation`,
`items.video_url`,
'time_group.id',
'time_group.name',
];
}

View File

@ -24,7 +24,7 @@ export class IndexItemQueueManager extends BaseIndexManager<ItemQueueEntity> {
get relations(): RelationParam {
return {
joinRelations: [],
selectRelations: ['items'],
selectRelations: ['items', 'items.time_group'],
countRelations: [],
};
}
@ -43,7 +43,7 @@ export class IndexItemQueueManager extends BaseIndexManager<ItemQueueEntity> {
`${this.tableName}.call_preparation`,
`${this.tableName}.use_notification`,
`${this.tableName}.requiring_notification`,
`${this.tableName}.usage_type`,
`items.id`,
`items.created_at`,
`items.status`,
@ -55,6 +55,9 @@ export class IndexItemQueueManager extends BaseIndexManager<ItemQueueEntity> {
`items.base_price`,
`items.share_profit`,
`items.play_estimation`,
'time_group.id',
'time_group.name',
];
}

View File

@ -76,6 +76,7 @@ export class IndexItemRateManager extends BaseIndexManager<ItemEntity> {
'item_rates',
'item_rates.season_period',
'season_period.season_type',
'time_group',
],
// relation yang hanya ingin dihitung (akan return number)
@ -113,6 +114,9 @@ export class IndexItemRateManager extends BaseIndexManager<ItemEntity> {
'season_type.id',
'season_type.name',
'time_group.id',
'time_group.name',
];
}

View File

@ -17,6 +17,8 @@ import { UserModel } from 'src/modules/user-related/user/data/models/user.model'
import { ItemRateModel } from 'src/modules/item-related/item-rate/data/models/item-rate.model';
import { GateModel } from 'src/modules/web-information/gate/data/models/gate.model';
import { ItemQueueModel } from 'src/modules/item-related/item-queue/data/models/item-queue.model';
import { TimeGroupModel } from 'src/modules/item-related/time-group/data/models/time-group.model';
import { UsageType } from 'src/modules/item-related/item-queue/constants';
@Entity(TABLE_NAME.ITEM)
export class ItemModel
@ -26,6 +28,9 @@ export class ItemModel
@Column('varchar', { name: 'name', unique: true })
name: string;
@Column('text', { name: 'booking_description', nullable: true })
booking_description: string;
@Column('varchar', { name: 'image_url', nullable: true })
image_url: string;
@ -39,6 +44,13 @@ export class ItemModel
})
item_type: ItemType;
@Column('enum', {
name: 'usage_type',
enum: UsageType,
default: UsageType.ONE_TIME,
})
usage_type: UsageType;
@Column('bigint', { name: 'hpp', nullable: true })
hpp: number;
@ -86,6 +98,17 @@ export class ItemModel
@JoinColumn({ name: 'item_category_id' })
item_category: ItemCategoryModel;
// start relation to time group
@Column('varchar', { name: 'time_group_id', nullable: true })
time_group_id: number;
@ManyToOne(() => TimeGroupModel, (model) => model.items, {
onUpdate: 'CASCADE',
onDelete: 'CASCADE',
})
@JoinColumn({ name: 'time_group_id' })
time_group: TimeGroupModel;
// end relation to time group
@ManyToOne(() => ItemQueueModel, (model) => model.items, {
onUpdate: 'CASCADE',
onDelete: 'SET NULL',

View File

@ -1,7 +1,8 @@
import { BaseStatusEntity } from 'src/core/modules/domain/entities/base-status.entity';
import { ItemType } from 'src/modules/item-related/item-category/constants';
import { LimitType } from '../../constants';
import { ItemRateEntity } from 'src/modules/item-related/item-rate/domain/entities/item-rate.entity';
import { UsageType } from 'src/modules/item-related/item-queue/constants';
export interface ItemEntity extends BaseStatusEntity {
name: string;
item_type: ItemType;
@ -18,4 +19,8 @@ export interface ItemEntity extends BaseStatusEntity {
use_queue: boolean;
show_to_booking: boolean;
breakdown_bundling?: boolean;
booking_description?: string;
usage_type?: UsageType;
item_rates?: ItemRateEntity[] | any[];
}

View File

@ -23,7 +23,13 @@ export class DetailItemManager extends BaseDetailManager<ItemEntity> {
joinRelations: [],
// relation join and select (relasi yang ingin ditampilkan),
selectRelations: ['item_category', 'bundling_items', 'tenant'],
selectRelations: [
'item_category',
'bundling_items',
'bundling_items.time_group bundling_time_groups',
'tenant',
'time_group',
],
// relation yang hanya ingin dihitung (akan return number)
countRelations: [],
@ -47,9 +53,11 @@ export class DetailItemManager extends BaseDetailManager<ItemEntity> {
`${this.tableName}.total_price`,
`${this.tableName}.base_price`,
`${this.tableName}.use_queue`,
`${this.tableName}.usage_type`,
`${this.tableName}.show_to_booking`,
`${this.tableName}.breakdown_bundling`,
`${this.tableName}.play_estimation`,
`${this.tableName}.booking_description`,
`item_category.id`,
`item_category.name`,
@ -59,8 +67,14 @@ export class DetailItemManager extends BaseDetailManager<ItemEntity> {
'bundling_items.hpp',
'bundling_items.base_price',
'bundling_time_groups.id',
'bundling_time_groups.name',
'tenant.id',
'tenant.name',
'time_group.id',
'time_group.name',
];
}

View File

@ -27,7 +27,12 @@ export class IndexItemManager extends BaseIndexManager<ItemEntity> {
joinRelations: [],
// relation join and select (relasi yang ingin ditampilkan),
selectRelations: ['item_category', 'bundling_items', 'tenant'],
selectRelations: [
'item_category',
'bundling_items',
'tenant',
'time_group',
],
// relation yang hanya ingin dihitung (akan return number)
countRelations: [],
@ -48,6 +53,9 @@ export class IndexItemManager extends BaseIndexManager<ItemEntity> {
`${this.tableName}.share_profit`,
`${this.tableName}.breakdown_bundling`,
`${this.tableName}.play_estimation`,
`${this.tableName}.show_to_booking`,
`${this.tableName}.booking_description`,
`${this.tableName}.usage_type`,
`item_category.id`,
`item_category.name`,
@ -57,6 +65,9 @@ export class IndexItemManager extends BaseIndexManager<ItemEntity> {
'tenant.id',
'tenant.name',
'time_group.id',
'time_group.name',
];
}
@ -98,10 +109,29 @@ export class IndexItemManager extends BaseIndexManager<ItemEntity> {
queryBuilder.andWhere(`${this.tableName}.tenant_id Is Null`);
}
if (this.filterParam.time_group_ids?.length) {
queryBuilder.andWhere(
`(${this.tableName}.time_group_id In (:...timeGroupIds) OR ${this.tableName}.time_group_id Is Null)`,
{
timeGroupIds: this.filterParam.time_group_ids,
},
);
}
if (this.filterParam.show_to_booking) {
queryBuilder.andWhere(`${this.tableName}.show_to_booking = true`);
}
if (this.filterParam.without_time_group != null) {
const withoutTimeGroup = this.filterParam.without_time_group
? 'Is Null'
: 'Is Not Null';
queryBuilder.andWhere(
`${this.tableName}.time_group_id ${withoutTimeGroup}`,
);
}
return queryBuilder;
}
}

View File

@ -16,6 +16,12 @@ export class FilterItemDto extends BaseFilterDto implements FilterItemEntity {
})
season_period_ids: string[];
@ApiProperty({ type: ['string'], required: false })
@Transform((body) => {
return Array.isArray(body.value) ? body.value : [body.value];
})
time_group_ids: string[];
@ApiProperty({ type: ['string'], required: false })
@Transform((body) => {
return Array.isArray(body.value) ? body.value : [body.value];

View File

@ -138,6 +138,17 @@ export class ItemDto extends BaseStatusDto implements ItemEntity {
@ValidateIf((body) => body.show_to_booking)
show_to_booking: boolean;
@ApiProperty({
type: String,
required: false,
example: '...',
})
@ValidateIf((body) => body.show_to_booking)
@IsString({
message: 'Booking description is required when show to booking is enabled.',
})
booking_description: string;
@ApiProperty({
name: 'bundling_items',
type: [Object],

View File

@ -6,6 +6,7 @@ import {
Patch,
Post,
Put,
UseGuards,
} from '@nestjs/common';
import { ItemDataOrchestrator } from '../domain/usecases/item-data.orchestrator';
import { ItemDto } from './dto/item.dto';
@ -16,6 +17,7 @@ import { BatchResult } from 'src/core/response/domain/ok-response.interface';
import { BatchIdsDto } from 'src/core/modules/infrastructure/dto/base-batch.dto';
import { Public } from 'src/core/guards';
import { UpdateItemPriceDto } from './dto/update-item-price.dto';
import { OtpCheckerGuard } from 'src/core/guards/domain/otp-checker.guard';
@ApiTags(`${MODULE_NAME.ITEM.split('-').join(' ')} - data`)
@Controller(`v1/${MODULE_NAME.ITEM}`)
@ -29,6 +31,7 @@ export class ItemDataController {
return await this.orchestrator.create(data);
}
@Public(true)
@Post('update-price')
async updatePrice(@Body() body: UpdateItemPriceDto): Promise<any> {
return await this.orchestrator.updatePrice(body);
@ -40,6 +43,7 @@ export class ItemDataController {
}
@Patch(':id/active')
@UseGuards(OtpCheckerGuard)
async active(@Param('id') dataId: string): Promise<string> {
return await this.orchestrator.active(dataId);
}
@ -50,6 +54,7 @@ export class ItemDataController {
}
@Patch(':id/confirm')
@UseGuards(OtpCheckerGuard)
async confirm(@Param('id') dataId: string): Promise<string> {
return await this.orchestrator.confirm(dataId);
}
@ -70,6 +75,7 @@ export class ItemDataController {
}
@Put(':id')
@UseGuards(OtpCheckerGuard)
async update(
@Param('id') dataId: string,
@Body() data: ItemDto,

View File

@ -0,0 +1,29 @@
import { TABLE_NAME } from 'src/core/strings/constants/table.constants';
import { TimeGroupEntity } from '../../domain/entities/time-group.entity';
import { Column, Entity, OneToMany } from 'typeorm';
import { BaseStatusModel } from 'src/core/modules/data/model/base-status.model';
import { ItemModel } from 'src/modules/item-related/item/data/models/item.model';
@Entity(TABLE_NAME.TIME_GROUPS)
export class TimeGroupModel
extends BaseStatusModel<TimeGroupEntity>
implements TimeGroupEntity
{
@Column('varchar', { name: 'name' })
name: string;
@Column({ type: 'time' })
start_time: string;
@Column({ type: 'time' })
end_time: string;
@Column({ type: 'time' })
max_usage_time: string;
@OneToMany(() => ItemModel, (model) => model.time_group, {
onDelete: 'CASCADE',
onUpdate: 'CASCADE',
})
items: ItemModel[];
}

View File

@ -0,0 +1,17 @@
import { Injectable } from '@nestjs/common';
import { BaseDataService } from 'src/core/modules/data/service/base-data.service';
import { TimeGroupEntity } from '../../domain/entities/time-group.entity';
import { InjectRepository } from '@nestjs/typeorm';
import { TimeGroupModel } from '../models/time-group.model';
import { CONNECTION_NAME } from 'src/core/strings/constants/base.constants';
import { Repository } from 'typeorm';
@Injectable()
export class TimeGroupDataService extends BaseDataService<TimeGroupEntity> {
constructor(
@InjectRepository(TimeGroupModel, CONNECTION_NAME.DEFAULT)
private repo: Repository<TimeGroupModel>,
) {
super(repo);
}
}

View File

@ -0,0 +1,17 @@
import { Injectable } from '@nestjs/common';
import { TimeGroupEntity } from '../../domain/entities/time-group.entity';
import { InjectRepository } from '@nestjs/typeorm';
import { TimeGroupModel } from '../models/time-group.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 TimeGroupReadService extends BaseReadService<TimeGroupEntity> {
constructor(
@InjectRepository(TimeGroupModel, CONNECTION_NAME.DEFAULT)
private repo: Repository<TimeGroupModel>,
) {
super(repo);
}
}

View File

@ -0,0 +1,5 @@
import { IEvent } from 'src/core/strings/constants/interface.constants';
export class TimeGroupChangeStatusEvent {
constructor(public readonly data: IEvent) {}
}

View File

@ -0,0 +1,5 @@
import { IEvent } from 'src/core/strings/constants/interface.constants';
export class TimeGroupCreatedEvent {
constructor(public readonly data: IEvent) {}
}

View File

@ -0,0 +1,5 @@
import { IEvent } from 'src/core/strings/constants/interface.constants';
export class TimeGroupDeletedEvent {
constructor(public readonly data: IEvent) {}
}

View File

@ -0,0 +1,5 @@
import { IEvent } from 'src/core/strings/constants/interface.constants';
export class TimeGroupUpdatedEvent {
constructor(public readonly data: IEvent) {}
}

View File

@ -0,0 +1,11 @@
import { BaseFilterEntity } from 'src/core/modules/domain/entities/base-filter.entity';
export interface FilterITimeGroupEntity extends BaseFilterEntity {
names: string[];
start_time_from: string;
start_time_to: string;
end_time_from: string;
end_time_to: string;
max_usage_time_from: string;
max_usage_time_to: string;
}

View File

@ -0,0 +1,8 @@
import { BaseStatusEntity } from 'src/core/modules/domain/entities/base-status.entity';
export interface TimeGroupEntity extends BaseStatusEntity {
name: string;
start_time: string;
end_time: string;
max_usage_time: string;
}

View File

@ -0,0 +1,45 @@
import { Injectable } from '@nestjs/common';
import { BaseUpdateStatusManager } from 'src/core/modules/domain/usecase/managers/base-update-status.manager';
import { TimeGroupEntity } from '../../entities/time-group.entity';
import {
EventTopics,
validateRelations,
} from 'src/core/strings/constants/interface.constants';
import { TimeGroupModel } from '../../../data/models/time-group.model';
import { TimeGroupChangeStatusEvent } from '../../entities/event/time-group-change-status.event';
@Injectable()
export class ActiveTimeGroupManager extends BaseUpdateStatusManager<TimeGroupEntity> {
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 TimeGroupModel;
}
get eventTopics(): EventTopics[] {
return [
{
topic: TimeGroupChangeStatusEvent,
data: this.data,
},
];
}
}

View File

@ -0,0 +1,45 @@
import { BaseBatchUpdateStatusManager } from 'src/core/modules/domain/usecase/managers/base-batch-update-status.manager';
import { TimeGroupEntity } from '../../entities/time-group.entity';
import {
EventTopics,
validateRelations,
} from 'src/core/strings/constants/interface.constants';
import { TimeGroupModel } from '../../../data/models/time-group.model';
import { TimeGroupChangeStatusEvent } from '../../entities/event/time-group-change-status.event';
import { BatchResult } from 'src/core/response/domain/ok-response.interface';
import { Injectable } from '@nestjs/common';
@Injectable()
export class BatchActiveTimeGroupManager extends BaseBatchUpdateStatusManager<TimeGroupEntity> {
validateData(data: TimeGroupEntity): Promise<void> {
return;
}
beforeProcess(): Promise<void> {
return;
}
afterProcess(): Promise<void> {
return;
}
get validateRelations(): validateRelations[] {
return [];
}
get entityTarget(): any {
return TimeGroupModel;
}
get eventTopics(): EventTopics[] {
return [
{
topic: TimeGroupChangeStatusEvent,
},
];
}
getResult(): BatchResult {
return this.result;
}
}

View File

@ -0,0 +1,45 @@
import { BaseBatchUpdateStatusManager } from 'src/core/modules/domain/usecase/managers/base-batch-update-status.manager';
import { TimeGroupEntity } from '../../entities/time-group.entity';
import {
EventTopics,
validateRelations,
} from 'src/core/strings/constants/interface.constants';
import { TimeGroupModel } from '../../../data/models/time-group.model';
import { TimeGroupChangeStatusEvent } from '../../entities/event/time-group-change-status.event';
import { BatchResult } from 'src/core/response/domain/ok-response.interface';
import { Injectable } from '@nestjs/common';
@Injectable()
export class BatchConfirmTimeGroupManager extends BaseBatchUpdateStatusManager<TimeGroupEntity> {
validateData(data: TimeGroupEntity): Promise<void> {
return;
}
beforeProcess(): Promise<void> {
return;
}
afterProcess(): Promise<void> {
return;
}
get validateRelations(): validateRelations[] {
return [];
}
get entityTarget(): any {
return TimeGroupModel;
}
get eventTopics(): EventTopics[] {
return [
{
topic: TimeGroupChangeStatusEvent,
},
];
}
getResult(): BatchResult {
return this.result;
}
}

View File

@ -0,0 +1,51 @@
import { BaseBatchDeleteManager } from 'src/core/modules/domain/usecase/managers/base-batch-delete.manager';
import { TimeGroupEntity } from '../../entities/time-group.entity';
import {
EventTopics,
validateRelations,
} from 'src/core/strings/constants/interface.constants';
import { TimeGroupModel } from '../../../data/models/time-group.model';
import { TimeGroupDeletedEvent } from '../../entities/event/time-group-deleted.event';
import { BatchResult } from 'src/core/response/domain/ok-response.interface';
import { Injectable } from '@nestjs/common';
@Injectable()
export class BatchDeleteTimeGroupManager extends BaseBatchDeleteManager<TimeGroupEntity> {
async beforeProcess(): Promise<void> {
return;
}
async validateData(data: TimeGroupEntity): Promise<void> {
return;
}
async afterProcess(): Promise<void> {
return;
}
get validateRelations(): validateRelations[] {
return [
{
relation: 'items',
message:
'Gagal! tidak dapat menghapus time group karena sudah berelasi dengan item',
},
];
}
get entityTarget(): any {
return TimeGroupModel;
}
get eventTopics(): EventTopics[] {
return [
{
topic: TimeGroupDeletedEvent,
},
];
}
getResult(): BatchResult {
return this.result;
}
}

View File

@ -0,0 +1,51 @@
import { BaseBatchUpdateStatusManager } from 'src/core/modules/domain/usecase/managers/base-batch-update-status.manager';
import { TimeGroupEntity } from '../../entities/time-group.entity';
import {
EventTopics,
validateRelations,
} from 'src/core/strings/constants/interface.constants';
import { TimeGroupModel } from '../../../data/models/time-group.model';
import { TimeGroupChangeStatusEvent } from '../../entities/event/time-group-change-status.event';
import { BatchResult } from 'src/core/response/domain/ok-response.interface';
import { Injectable } from '@nestjs/common';
@Injectable()
export class BatchInactiveTimeGroupManager extends BaseBatchUpdateStatusManager<TimeGroupEntity> {
validateData(data: TimeGroupEntity): Promise<void> {
return;
}
beforeProcess(): Promise<void> {
return;
}
afterProcess(): Promise<void> {
return;
}
get validateRelations(): validateRelations[] {
return [
{
relation: 'items',
message:
'Gagal! tidak dapat mengubah status time group karena sudah berelasi dengan item',
},
];
}
get entityTarget(): any {
return TimeGroupModel;
}
get eventTopics(): EventTopics[] {
return [
{
topic: TimeGroupChangeStatusEvent,
},
];
}
getResult(): BatchResult {
return this.result;
}
}

View File

@ -0,0 +1,45 @@
import { Injectable } from '@nestjs/common';
import { BaseUpdateStatusManager } from 'src/core/modules/domain/usecase/managers/base-update-status.manager';
import { TimeGroupEntity } from '../../entities/time-group.entity';
import {
EventTopics,
validateRelations,
} from 'src/core/strings/constants/interface.constants';
import { TimeGroupModel } from '../../../data/models/time-group.model';
import { TimeGroupChangeStatusEvent } from '../../entities/event/time-group-change-status.event';
@Injectable()
export class ConfirmTimeGroupManager extends BaseUpdateStatusManager<TimeGroupEntity> {
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 TimeGroupModel;
}
get eventTopics(): EventTopics[] {
return [
{
topic: TimeGroupChangeStatusEvent,
data: this.data,
},
];
}
}

View File

@ -0,0 +1,85 @@
import { Injectable } from '@nestjs/common';
import {
EventTopics,
columnUniques,
validateRelations,
} from 'src/core/strings/constants/interface.constants';
import { TimeGroupEntity } from '../../entities/time-group.entity';
import { TimeGroupModel } from '../../../data/models/time-group.model';
import { BaseCreateManager } from 'src/core/modules/domain/usecase/managers/base-create.manager';
import { TimeGroupCreatedEvent } from '../../entities/event/time-group-created.event';
import * as moment from 'moment';
@Injectable()
export class CreateTimeGroupManager extends BaseCreateManager<TimeGroupEntity> {
async beforeProcess(): Promise<void> {
const queryBuilder = this.dataService
.getRepository()
.createQueryBuilder(this.tableName);
const overlapping = await queryBuilder
.where(`${this.tableName}.start_time <= :end_time`, {
end_time: this.data.end_time,
})
.andWhere(`${this.tableName}.end_time >= :start_time`, {
start_time: this.data.start_time,
})
.getOne();
if (overlapping) {
throw new Error(
'Rentang waktu yang dimasukkan beririsan dengan data lain.',
);
} else if (this.data.max_usage_time) {
const format = 'HH:mm';
const end_time = moment(this.data.end_time, format);
const max_usage_time = moment(this.data.max_usage_time, format);
if (max_usage_time.isBefore(end_time)) {
throw new Error(
'Waktu maksimum penggunaan harus lebih besar dari waktu selesai.',
);
}
return;
} else if (this.data.start_time && this.data.end_time) {
const format = 'HH:mm';
const start_time = moment(this.data.start_time, format);
const end_time = moment(this.data.end_time, format);
if (end_time.isBefore(start_time)) {
throw new Error('Waktu akhir harus lebih besar dari waktu 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: TimeGroupCreatedEvent,
data: this.data,
},
];
}
get entityTarget(): any {
return TimeGroupModel;
}
}

View File

@ -0,0 +1,51 @@
import { Injectable } from '@nestjs/common';
import { BaseDeleteManager } from 'src/core/modules/domain/usecase/managers/base-delete.manager';
import { TimeGroupEntity } from '../../entities/time-group.entity';
import {
EventTopics,
validateRelations,
} from 'src/core/strings/constants/interface.constants';
import { TimeGroupModel } from '../../../data/models/time-group.model';
import { TimeGroupDeletedEvent } from '../../entities/event/time-group-deleted.event';
@Injectable()
export class DeleteTimeGroupManager extends BaseDeleteManager<TimeGroupEntity> {
getResult(): string {
return `Success`;
}
async validateProcess(): Promise<void> {
return;
}
async beforeProcess(): Promise<void> {
return;
}
async afterProcess(): Promise<void> {
return;
}
get validateRelations(): validateRelations[] {
return [
{
relation: 'items',
message:
'Gagal! tidak dapat menghapus time group karena sudah berelasi dengan item',
},
];
}
get entityTarget(): any {
return TimeGroupModel;
}
get eventTopics(): EventTopics[] {
return [
{
topic: TimeGroupDeletedEvent,
data: this.data,
},
];
}
}

View File

@ -0,0 +1,48 @@
import { Injectable } from '@nestjs/common';
import { BaseDetailManager } from 'src/core/modules/domain/usecase/managers/base-detail.manager';
import { TimeGroupEntity } from '../../entities/time-group.entity';
import { RelationParam } from 'src/core/modules/domain/entities/base-filter.entity';
@Injectable()
export class DetailTimeGroupManager extends BaseDetailManager<TimeGroupEntity> {
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}.start_time`,
`${this.tableName}.end_time`,
`${this.tableName}.max_usage_time`,
`${this.tableName}.created_at`,
`${this.tableName}.creator_name`,
`${this.tableName}.updated_at`,
`${this.tableName}.editor_name`,
];
}
get setFindProperties(): any {
return {
id: this.dataId,
};
}
}

View File

@ -0,0 +1,51 @@
import { Injectable } from '@nestjs/common';
import { BaseUpdateStatusManager } from 'src/core/modules/domain/usecase/managers/base-update-status.manager';
import { TimeGroupEntity } from '../../entities/time-group.entity';
import {
EventTopics,
validateRelations,
} from 'src/core/strings/constants/interface.constants';
import { TimeGroupModel } from '../../../data/models/time-group.model';
import { TimeGroupChangeStatusEvent } from '../../entities/event/time-group-change-status.event';
@Injectable()
export class InactiveTimeGroupManager extends BaseUpdateStatusManager<TimeGroupEntity> {
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 [
{
relation: 'items',
message:
'Gagal! tidak dapat mengubah status time group karena sudah berelasi dengan item',
},
];
}
get entityTarget(): any {
return TimeGroupModel;
}
get eventTopics(): EventTopics[] {
return [
{
topic: TimeGroupChangeStatusEvent,
data: this.data,
},
];
}
}

View File

@ -0,0 +1,65 @@
import { Injectable } from '@nestjs/common';
import { BaseIndexManager } from 'src/core/modules/domain/usecase/managers/base-index.manager';
import { TimeGroupEntity } from '../../entities/time-group.entity';
import { SelectQueryBuilder } from 'typeorm';
import {
Param,
RelationParam,
} from 'src/core/modules/domain/entities/base-filter.entity';
// TODO:
// Implementasikan filter by start_time, end_timen, dan max_usage_time
@Injectable()
export class IndexPublicTimeGroupManager extends BaseIndexManager<TimeGroupEntity> {
async prepareData(): Promise<void> {
return;
}
async beforeProcess(): Promise<void> {
return;
}
async afterProcess(): Promise<void> {
return;
}
get relations(): RelationParam {
return {
joinRelations: ['items'],
selectRelations: [],
countRelations: ['items'],
};
}
get selects(): string[] {
return [
`${this.tableName}.id`,
`${this.tableName}.status`,
`${this.tableName}.name`,
`${this.tableName}.start_time`,
`${this.tableName}.end_time`,
`${this.tableName}.max_usage_time`,
`${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<TimeGroupEntity>,
): SelectQueryBuilder<TimeGroupEntity> {
queryBuilder.andWhere(`items.id is not null`);
return queryBuilder;
}
}

View File

@ -0,0 +1,64 @@
import { Injectable } from '@nestjs/common';
import { BaseIndexManager } from 'src/core/modules/domain/usecase/managers/base-index.manager';
import { TimeGroupEntity } from '../../entities/time-group.entity';
import { SelectQueryBuilder } from 'typeorm';
import {
Param,
RelationParam,
} from 'src/core/modules/domain/entities/base-filter.entity';
// TODO:
// Implementasikan filter by start_time, end_timen, dan max_usage_time
@Injectable()
export class IndexTimeGroupManager extends BaseIndexManager<TimeGroupEntity> {
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}.start_time`,
`${this.tableName}.end_time`,
`${this.tableName}.max_usage_time`,
`${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<TimeGroupEntity>,
): SelectQueryBuilder<TimeGroupEntity> {
return queryBuilder;
}
}

View File

@ -0,0 +1,85 @@
import { Injectable } from '@nestjs/common';
import { BaseUpdateManager } from 'src/core/modules/domain/usecase/managers/base-update.manager';
import { TimeGroupEntity } from '../../entities/time-group.entity';
import { TimeGroupModel } from '../../../data/models/time-group.model';
import { TimeGroupUpdatedEvent } from '../../entities/event/time-group-updated.event';
import {
EventTopics,
columnUniques,
validateRelations,
} from 'src/core/strings/constants/interface.constants';
import * as moment from 'moment';
@Injectable()
export class UpdateTimeGroupManager extends BaseUpdateManager<TimeGroupEntity> {
async validateProcess(): Promise<void> {
const queryBuilder = this.dataService
.getRepository()
.createQueryBuilder(this.tableName);
const overlapping = await queryBuilder
.where(`${this.tableName}.start_time <= :end_time`, {
end_time: this.data.end_time,
})
.andWhere(`${this.tableName}.end_time >= :start_time`, {
start_time: this.data.start_time,
})
.andWhere(`${this.tableName}.id != :id`, { id: this.dataId ?? null })
.getOne();
if (overlapping) {
throw new Error(
'Rentang waktu yang dimasukkan beririsan dengan data lain.',
);
} else if (this.data.max_usage_time) {
const format = 'HH:mm';
const end_time = moment(this.data.end_time, format);
const max_usage_time = moment(this.data.max_usage_time, format);
if (max_usage_time.isBefore(end_time)) {
throw new Error(
'Waktu maksimum penggunaan harus lebih besar dari waktu selesai.',
);
}
return;
} else if (this.data.start_time && this.data.end_time) {
const format = 'HH:mm';
const start_time = moment(this.data.start_time, format);
const end_time = moment(this.data.end_time, format);
if (end_time.isBefore(start_time)) {
throw new Error('Waktu akhir harus lebih besar dari waktu mulai.');
}
return;
}
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 TimeGroupModel;
}
get eventTopics(): EventTopics[] {
return [
{
topic: TimeGroupUpdatedEvent,
},
];
}
}

View File

@ -0,0 +1,119 @@
import { Injectable } from '@nestjs/common';
import { CreateTimeGroupManager } from './managers/create-time-group.manager';
import { TimeGroupDataService } from '../../data/services/time-group-data.service';
import { TimeGroupEntity } from '../entities/time-group.entity';
import { DeleteTimeGroupManager } from './managers/delete-time-group.manager';
import { UpdateTimeGroupManager } from './managers/update-time-group.manager';
import { BaseDataTransactionOrchestrator } from 'src/core/modules/domain/usecase/orchestrators/base-data-transaction.orchestrator';
import { ActiveTimeGroupManager } from './managers/active-time-group.manager';
import { InactiveTimeGroupManager } from './managers/inactive-time-group.manager';
import { ConfirmTimeGroupManager } from './managers/confirm-time-group.manager';
import { STATUS } from 'src/core/strings/constants/base.constants';
import { BatchResult } from 'src/core/response/domain/ok-response.interface';
import { BatchConfirmTimeGroupManager } from './managers/batch-confirm-time-group.manager';
import { BatchInactiveTimeGroupManager } from './managers/batch-inactive-time-group.manager';
import { BatchActiveTimeGroupManager } from './managers/batch-active-time-group.manager';
import { BatchDeleteTimeGroupManager } from './managers/batch-delete-time-group.manager';
import { TABLE_NAME } from 'src/core/strings/constants/table.constants';
@Injectable()
export class TimeGroupDataOrchestrator extends BaseDataTransactionOrchestrator<TimeGroupEntity> {
constructor(
private createManager: CreateTimeGroupManager,
private updateManager: UpdateTimeGroupManager,
private deleteManager: DeleteTimeGroupManager,
private activeManager: ActiveTimeGroupManager,
private confirmManager: ConfirmTimeGroupManager,
private inactiveManager: InactiveTimeGroupManager,
private batchDeleteManager: BatchDeleteTimeGroupManager,
private batchActiveManager: BatchActiveTimeGroupManager,
private batchConfirmManager: BatchConfirmTimeGroupManager,
private batchInactiveManager: BatchInactiveTimeGroupManager,
private serviceData: TimeGroupDataService,
) {
super();
}
async create(data): Promise<TimeGroupEntity> {
this.createManager.setData(data);
this.createManager.setService(this.serviceData, TABLE_NAME.TIME_GROUPS);
await this.createManager.execute();
await this.createManager.generateConfig();
return this.createManager.getResult();
}
async update(dataId, data): Promise<TimeGroupEntity> {
this.updateManager.setData(dataId, data);
this.updateManager.setService(this.serviceData, TABLE_NAME.TIME_GROUPS);
await this.updateManager.execute();
return this.updateManager.getResult();
}
async delete(dataId): Promise<string> {
this.deleteManager.setData(dataId);
this.deleteManager.setService(this.serviceData, TABLE_NAME.TIME_GROUPS);
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.TIME_GROUPS,
);
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.TIME_GROUPS);
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.TIME_GROUPS,
);
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.TIME_GROUPS);
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.TIME_GROUPS,
);
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.TIME_GROUPS);
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.TIME_GROUPS,
);
await this.batchInactiveManager.execute();
return this.batchInactiveManager.getResult();
}
}

View File

@ -0,0 +1,45 @@
import { Injectable } from '@nestjs/common';
import { IndexTimeGroupManager } from './managers/index-time-group.manager';
import { TimeGroupReadService } from '../../data/services/time-group-read.service';
import { TimeGroupEntity } from '../entities/time-group.entity';
import { PaginationResponse } from 'src/core/response/domain/ok-response.interface';
import { BaseReadOrchestrator } from 'src/core/modules/domain/usecase/orchestrators/base-read.orchestrator';
import { DetailTimeGroupManager } from './managers/detail-time-group.manager';
import { TABLE_NAME } from 'src/core/strings/constants/table.constants';
import { IndexPublicTimeGroupManager } from './managers/index-public-time-group.manager';
@Injectable()
export class TimeGroupReadOrchestrator extends BaseReadOrchestrator<TimeGroupEntity> {
constructor(
private indexManager: IndexTimeGroupManager,
private indexPublicManager: IndexPublicTimeGroupManager,
private detailManager: DetailTimeGroupManager,
private serviceData: TimeGroupReadService,
) {
super();
}
async index(params): Promise<PaginationResponse<TimeGroupEntity>> {
this.indexManager.setFilterParam(params);
this.indexManager.setService(this.serviceData, TABLE_NAME.TIME_GROUPS);
await this.indexManager.execute();
return this.indexManager.getResult();
}
async indexPublic(params): Promise<PaginationResponse<TimeGroupEntity>> {
this.indexPublicManager.setFilterParam(params);
this.indexPublicManager.setService(
this.serviceData,
TABLE_NAME.TIME_GROUPS,
);
await this.indexPublicManager.execute();
return this.indexPublicManager.getResult();
}
async detail(dataId: string): Promise<TimeGroupEntity> {
this.detailManager.setData(dataId);
this.detailManager.setService(this.serviceData, TABLE_NAME.TIME_GROUPS);
await this.detailManager.execute();
return this.detailManager.getResult();
}
}

View File

@ -0,0 +1,33 @@
import { BaseFilterDto } from 'src/core/modules/infrastructure/dto/base-filter.dto';
import { FilterITimeGroupEntity } from '../../domain/entities/filter-time-group.entity';
import { ApiProperty } from '@nestjs/swagger';
import { ValidateIf } from 'class-validator';
export class FilterTimeGroupDto
extends BaseFilterDto
implements FilterITimeGroupEntity
{
@ApiProperty({ type: 'string', required: false })
@ValidateIf((body) => body.start_time_from)
start_time_from: string;
@ApiProperty({ type: 'string', required: false })
@ValidateIf((body) => body.start_time_to)
start_time_to: string;
@ApiProperty({ type: 'string', required: false })
@ValidateIf((body) => body.end_time_from)
end_time_from: string;
@ApiProperty({ type: 'string', required: false })
@ValidateIf((body) => body.end_time_to)
end_time_to: string;
@ApiProperty({ type: 'string', required: false })
@ValidateIf((body) => body.max_usage_time_from)
max_usage_time_from: string;
@ApiProperty({ type: 'string', required: false })
@ValidateIf((body) => body.max_usage_time_to)
max_usage_time_to: string;
}

View File

@ -0,0 +1,47 @@
import { BaseStatusDto } from 'src/core/modules/infrastructure/dto/base-status.dto';
import { TimeGroupEntity } from '../../domain/entities/time-group.entity';
import { IsString, ValidateIf } from 'class-validator';
import { ApiProperty } from '@nestjs/swagger';
export class CreateTimeGroupDto
extends BaseStatusDto
implements TimeGroupEntity
{
@ApiProperty({ name: 'name', required: true, example: 'Morning' })
@IsString()
name: string;
@ApiProperty({ name: 'start_time', required: true, example: '09:00' })
@IsString()
start_time: string;
@ApiProperty({ name: 'end_time', required: true, example: '10:00' })
@IsString()
end_time: string;
@ApiProperty({ name: 'max_usage_time', required: true, example: '10:30' })
@IsString()
max_usage_time: string;
}
export class EditTimeGroupDto extends BaseStatusDto implements TimeGroupEntity {
@ApiProperty({ name: 'name', example: 'Morning' })
@IsString()
@ValidateIf((body) => body.name)
name: string;
@ApiProperty({ name: 'start_time', example: '09:00' })
@IsString()
@ValidateIf((body) => body.start_time)
start_time: string;
@ApiProperty({ name: 'end_time', example: '10:00' })
@IsString()
@ValidateIf((body) => body.end_time)
end_time: string;
@ApiProperty({ name: 'max_usage_time', example: '10:30' })
@IsString()
@ValidateIf((body) => body.max_usage_time)
max_usage_time: string;
}

View File

@ -0,0 +1,78 @@
import {
Body,
Controller,
Delete,
Param,
Patch,
Post,
Put,
} from '@nestjs/common';
import { TimeGroupDataOrchestrator } from '../domain/usecases/time-group-data.orchestrator';
import { CreateTimeGroupDto, EditTimeGroupDto } from './dto/time-group.dto';
import { MODULE_NAME } from 'src/core/strings/constants/module.constants';
import { ApiBearerAuth, ApiTags } from '@nestjs/swagger';
import { TimeGroupEntity } from '../domain/entities/time-group.entity';
import { BatchResult } from 'src/core/response/domain/ok-response.interface';
import { BatchIdsDto } from 'src/core/modules/infrastructure/dto/base-batch.dto';
import { Public } from 'src/core/guards';
@ApiTags(`${MODULE_NAME.TIME_GROUPS.split('-').join(' ')} - data`)
@Controller(`v1/${MODULE_NAME.TIME_GROUPS}`)
@Public(false)
@ApiBearerAuth('JWT')
export class TimeGroupDataController {
constructor(private orchestrator: TimeGroupDataOrchestrator) {}
@Post()
async create(@Body() data: CreateTimeGroupDto): Promise<TimeGroupEntity> {
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: EditTimeGroupDto,
): Promise<TimeGroupEntity> {
return await this.orchestrator.update(dataId, data);
}
@Delete(':id')
async delete(@Param('id') dataId: string): Promise<string> {
return await this.orchestrator.delete(dataId);
}
}

View File

@ -0,0 +1,46 @@
import { Controller, Get, Param, Query } from '@nestjs/common';
import { FilterTimeGroupDto } from './dto/filter-time-group.dto';
import { Pagination } from 'src/core/response';
import { PaginationResponse } from 'src/core/response/domain/ok-response.interface';
import { TimeGroupEntity } from '../domain/entities/time-group.entity';
import { TimeGroupReadOrchestrator } from '../domain/usecases/time-group-read.orchestrator';
import { ApiBearerAuth, ApiTags } from '@nestjs/swagger';
import { MODULE_NAME } from 'src/core/strings/constants/module.constants';
import { Public } from 'src/core/guards';
@ApiTags(`${MODULE_NAME.TIME_GROUPS.split('-').join(' ')} - read`)
@Controller(`v1/${MODULE_NAME.TIME_GROUPS}`)
@Public(false)
@ApiBearerAuth('JWT')
export class TimeGroupReadController {
constructor(private orchestrator: TimeGroupReadOrchestrator) {}
@Get()
@Pagination()
async index(
@Query() params: FilterTimeGroupDto,
): Promise<PaginationResponse<TimeGroupEntity>> {
return await this.orchestrator.index(params);
}
@Get(':id')
async detail(@Param('id') id: string): Promise<TimeGroupEntity> {
return await this.orchestrator.detail(id);
}
}
@ApiTags(`${MODULE_NAME.TIME_GROUPS.split('-').join(' ')} List- read`)
// @Controller(`v1/${MODULE_NAME.TIME_GROUPS}-list`)
@Controller(``)
@Public()
export class TimeGroupPublicReadController {
constructor(private orchestrator: TimeGroupReadOrchestrator) {}
@Get('v1/time-group-list-by-items')
@Pagination()
async indexPublic(
@Query() params: FilterTimeGroupDto,
): Promise<PaginationResponse<TimeGroupEntity>> {
return await this.orchestrator.indexPublic(params);
}
}

View File

@ -0,0 +1,63 @@
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 { TimeGroupDataService } from './data/services/time-group-data.service';
import { TimeGroupReadService } from './data/services/time-group-read.service';
import {
TimeGroupPublicReadController,
TimeGroupReadController,
} from './infrastructure/time-group-read.controller';
import { TimeGroupReadOrchestrator } from './domain/usecases/time-group-read.orchestrator';
import { TimeGroupDataController } from './infrastructure/time-group-data.controller';
import { TimeGroupDataOrchestrator } from './domain/usecases/time-group-data.orchestrator';
import { CreateTimeGroupManager } from './domain/usecases/managers/create-time-group.manager';
import { CqrsModule } from '@nestjs/cqrs';
import { IndexTimeGroupManager } from './domain/usecases/managers/index-time-group.manager';
import { DeleteTimeGroupManager } from './domain/usecases/managers/delete-time-group.manager';
import { UpdateTimeGroupManager } from './domain/usecases/managers/update-time-group.manager';
import { ActiveTimeGroupManager } from './domain/usecases/managers/active-time-group.manager';
import { ConfirmTimeGroupManager } from './domain/usecases/managers/confirm-time-group.manager';
import { InactiveTimeGroupManager } from './domain/usecases/managers/inactive-time-group.manager';
import { DetailTimeGroupManager } from './domain/usecases/managers/detail-time-group.manager';
import { BatchDeleteTimeGroupManager } from './domain/usecases/managers/batch-delete-time-group.manager';
import { BatchActiveTimeGroupManager } from './domain/usecases/managers/batch-active-time-group.manager';
import { BatchConfirmTimeGroupManager } from './domain/usecases/managers/batch-confirm-time-group.manager';
import { BatchInactiveTimeGroupManager } from './domain/usecases/managers/batch-inactive-time-group.manager';
import { TimeGroupModel } from './data/models/time-group.model';
import { IndexPublicTimeGroupManager } from './domain/usecases/managers/index-public-time-group.manager';
@Module({
imports: [
ConfigModule.forRoot(),
TypeOrmModule.forFeature([TimeGroupModel], CONNECTION_NAME.DEFAULT),
CqrsModule,
],
controllers: [
TimeGroupDataController,
TimeGroupReadController,
TimeGroupPublicReadController,
],
providers: [
IndexPublicTimeGroupManager,
IndexTimeGroupManager,
DetailTimeGroupManager,
CreateTimeGroupManager,
DeleteTimeGroupManager,
UpdateTimeGroupManager,
ActiveTimeGroupManager,
ConfirmTimeGroupManager,
InactiveTimeGroupManager,
BatchDeleteTimeGroupManager,
BatchActiveTimeGroupManager,
BatchConfirmTimeGroupManager,
BatchInactiveTimeGroupManager,
TimeGroupDataService,
TimeGroupReadService,
TimeGroupDataOrchestrator,
TimeGroupReadOrchestrator,
],
})
export class TimeGroupModule {}

View File

@ -40,11 +40,14 @@ export class TicketDataService extends BaseDataService<QueueTicket> {
}
async loginQueue(id: string): Promise<QueueOrder> {
const start = moment().startOf('day').valueOf();
const end = moment().endOf('day').valueOf();
const order = await this.order.findOne({
relations: ['tickets'],
where: [
{ transaction_id: id },
{ code: id, transaction_id: Not(IsNull()) },
{ transaction_id: id, date: Between(start, end) },
{ code: id, transaction_id: Not(IsNull()), date: Between(start, end) },
],
});

View File

@ -39,7 +39,7 @@ import { ItemQueueModel } from '../item-related/item-queue/data/models/item-queu
import { QueueTimeFormula } from './domain/usecases/formula/queue-time.formula';
import { QueueJobController } from './infrastructure/controllers/queue-job.controller';
import { GenerateQueueManager } from './domain/usecases/generate-queue.manager';
import { CouchModule } from 'src/modules/configuration/couch/couch.module';
@Module({
imports: [
ConfigModule.forRoot(),
@ -57,6 +57,7 @@ import { GenerateQueueManager } from './domain/usecases/generate-queue.manager';
CONNECTION_NAME.DEFAULT,
),
CqrsModule,
CouchModule,
],
controllers: [QueueController, QueueAdminController, QueueJobController],
providers: [

View File

@ -84,6 +84,13 @@ export default <ReportConfigEntity>{
type: DATA_TYPE.DIMENSION,
format: DATA_FORMAT.TEXT,
},
{
column: 'main__otp_code',
query: 'main.otp_code',
label: 'Kode OTP',
type: DATA_TYPE.DIMENSION,
format: DATA_FORMAT.TEXT,
},
{
column: 'main__payment_code',
query: `CASE WHEN main.type = 'counter' THEN main.invoice_code ELSE main.payment_code END`,

View File

@ -119,6 +119,14 @@ export default <ReportConfigEntity>{
type: DATA_TYPE.DIMENSION,
format: DATA_FORMAT.TEXT,
},
{
column: 'vip__otp_code',
query: 'vip.otp_code',
label: 'Kode OTP',
type: DATA_TYPE.DIMENSION,
format: DATA_FORMAT.TEXT,
},
{
column: 'privilege__name',
query: 'privilege.name',

View File

@ -19,6 +19,7 @@ export default <ReportConfigEntity>{
LEFT JOIN refunds refund ON refund.transaction_id = main.id
LEFT JOIN refund_items refund_item ON refund_item.refund_item_id = tr_item.item_id::uuid
LEFT JOIN items item ON item.id::text = tr_item.item_id::text
LEFT JOIN time_groups tg on tg.id = item.time_group_id
LEFT JOIN users tenant ON tenant.id::text = item.tenant_id::text`,
main_table_alias: 'main',
whereDefaultConditions: [
@ -111,6 +112,13 @@ export default <ReportConfigEntity>{
type: DATA_TYPE.DIMENSION,
format: DATA_FORMAT.TEXT,
},
{
column: 'tg__name',
query: 'tg.name',
label: 'Time Group',
type: DATA_TYPE.DIMENSION,
format: DATA_FORMAT.TEXT,
},
{
column: 'tr_item__item_name',
query: `CASE WHEN tr_item.item_type = 'bundling' THEN tr_item_bundling.item_name ELSE tr_item.item_name END`,
@ -338,6 +346,12 @@ export default <ReportConfigEntity>{
field_type: FILTER_FIELD_TYPE.input_tag,
filter_type: FILTER_TYPE.TEXT_MULTIPLE_CONTAINS,
},
{
filed_label: 'Time Group',
filter_column: 'tg__name',
field_type: FILTER_FIELD_TYPE.input_tag,
filter_type: FILTER_TYPE.TEXT_MULTIPLE_CONTAINS,
},
{
filed_label: 'Tipe Pelanggan',
filter_column: 'main__customer_type',

View File

@ -18,6 +18,7 @@ export default <ReportConfigEntity>{
LEFT JOIN refunds refund ON refund.transaction_id = main.id
LEFT JOIN refund_items refund_item ON refund_item.refund_item_id = tr_item.item_id::uuid
LEFT JOIN items item ON item.id::text = tr_item.item_id::text
LEFT JOIN time_groups tg on tg.id = item.time_group_id
LEFT JOIN users tenant ON tenant.id::text = item.tenant_id::text`,
main_table_alias: 'main',
whereDefaultConditions: [
@ -109,6 +110,13 @@ export default <ReportConfigEntity>{
type: DATA_TYPE.DIMENSION,
format: DATA_FORMAT.TEXT,
},
{
column: 'tg__name',
query: 'tg.name',
label: 'Time Group',
type: DATA_TYPE.DIMENSION,
format: DATA_FORMAT.TEXT,
},
{
column: 'main__customer_type',
query: 'main.customer_type',
@ -296,6 +304,12 @@ export default <ReportConfigEntity>{
field_type: FILTER_FIELD_TYPE.input_tag,
filter_type: FILTER_TYPE.TEXT_MULTIPLE_CONTAINS,
},
{
filed_label: 'Time Group',
filter_column: 'tg__name',
field_type: FILTER_FIELD_TYPE.input_tag,
filter_type: FILTER_TYPE.TEXT_MULTIPLE_CONTAINS,
},
{
filed_label: 'Tipe Pelanggan',
filter_column: 'main__customer_type',

View File

@ -50,6 +50,13 @@ export default <ReportConfigEntity>{
type: DATA_TYPE.DIMENSION,
format: DATA_FORMAT.TEXT,
},
{
column: 'main__otp_code',
query: 'main.otp_code',
label: 'Kode OTP Reject',
type: DATA_TYPE.DIMENSION,
format: DATA_FORMAT.TEXT,
},
{
column: 'main__payment_date',
query: `CASE WHEN main.payment_date is not null THEN to_char(main.payment_date, 'DD-MM-YYYY') ELSE null END`,

View File

@ -35,6 +35,13 @@ export default <ReportConfigEntity>{
type: DATA_TYPE.DIMENSION,
format: DATA_FORMAT.TEXT,
},
{
column: 'main__otp_code',
query: 'main.otp_code',
label: 'Kode OTP',
type: DATA_TYPE.DIMENSION,
format: DATA_FORMAT.TEXT,
},
{
column: 'main__discount',
query: 'CASE WHEN main.discount > 0 THEN main.discount ELSE null END',

View File

@ -28,7 +28,12 @@ export class IndexSeasonPeriodeItemManager extends BaseIndexManager<ItemRateEnti
joinRelations: [],
// relation join and select (relasi yang ingin ditampilkan),
selectRelations: ['item', 'item.item_category', 'item.bundling_items'],
selectRelations: [
'item',
'item.item_category',
'item.bundling_items',
'item.time_group',
],
// relation yang hanya ingin dihitung (akan return number)
countRelations: [],
@ -57,6 +62,9 @@ export class IndexSeasonPeriodeItemManager extends BaseIndexManager<ItemRateEnti
'bundling_items.id',
'bundling_items.name',
'time_group.id',
'time_group.name',
];
}

View File

@ -6,6 +6,7 @@ import {
Patch,
Post,
Put,
UseGuards,
} from '@nestjs/common';
import { SeasonPeriodDataOrchestrator } from '../domain/usecases/season-period-data.orchestrator';
import { SeasonPeriodDto } from './dto/season-period.dto';
@ -18,6 +19,7 @@ import { Public } from 'src/core/guards';
import { UpdateSeasonPeriodDto } from './dto/update-season-period.dto';
import { UpdateSeasonPeriodItemDto } from './dto/update-season-period-item.dto';
import { UpdateSeasonPriceDto } from './dto/update-season-price.dto';
import { OtpCheckerGuard } from 'src/core/guards/domain/otp-checker.guard';
@ApiTags(`${MODULE_NAME.SEASON_PERIOD.split('-').join(' ')} - data`)
@Controller(`v1/${MODULE_NAME.SEASON_PERIOD}`)
@ -27,11 +29,13 @@ export class SeasonPeriodDataController {
constructor(private orchestrator: SeasonPeriodDataOrchestrator) {}
@Post()
@UseGuards(OtpCheckerGuard)
async create(@Body() data: SeasonPeriodDto): Promise<SeasonPeriodEntity> {
return await this.orchestrator.create(data);
}
@Post('/update-price')
@UseGuards(OtpCheckerGuard)
async updatePrice(@Body() body: UpdateSeasonPriceDto): Promise<BatchResult> {
return await this.orchestrator.updatePrice(body);
}
@ -80,7 +84,9 @@ export class SeasonPeriodDataController {
}
// pemisahan update data dengan update items dikarenakan payload (based on tampilan) berbeda
// TODO => simpan OTP update yang disikim dari request ini
@Put(':id/items')
@UseGuards(OtpCheckerGuard)
async updateItems(
@Param('id') dataId: string,
@Body() data: UpdateSeasonPeriodItemDto,

View File

@ -15,6 +15,12 @@ import { TransactionEntity } from 'src/modules/transaction/transaction/domain/en
@Injectable()
export class CancelReconciliationManager extends BaseUpdateStatusManager<TransactionEntity> {
protected payloadBody: any;
setCustomBodyRequest(body) {
this.payloadBody = body;
}
getResult(): string {
return `Success active data ${this.result.id}`;
}
@ -50,6 +56,7 @@ export class CancelReconciliationManager extends BaseUpdateStatusManager<Transac
async beforeProcess(): Promise<void> {
if (this.data.is_recap_transaction) {
Object.assign(this.data, {
otp_code: this.payloadBody?.otp_code,
reconciliation_confirm_by: null,
reconciliation_confirm_date: null,
reconciliation_status: STATUS.PENDING,
@ -58,6 +65,7 @@ export class CancelReconciliationManager extends BaseUpdateStatusManager<Transac
});
} else {
Object.assign(this.data, {
otp_code: this.payloadBody?.otp_code,
reconciliation_mdr: this.data.reconciliation_mdr ?? null,
reconciliation_confirm_by: this.user.name,
reconciliation_confirm_date: new Date().getTime(),
@ -70,6 +78,7 @@ export class CancelReconciliationManager extends BaseUpdateStatusManager<Transac
: this.data.settlement_date,
});
}
return;
}

View File

@ -58,9 +58,10 @@ export class ReconciliationDataOrchestrator {
return this.batchConfirmManager.getResult();
}
async cancel(dataId): Promise<string> {
async cancel(dataId, body): Promise<string> {
this.cancelManager.setData(dataId, STATUS.REJECTED);
this.cancelManager.setService(this.serviceData, TABLE_NAME.TRANSACTION);
this.cancelManager.setCustomBodyRequest(body);
await this.cancelManager.execute();
return this.cancelManager.getResult();
}

View File

@ -0,0 +1,14 @@
import { ApiProperty } from '@nestjs/swagger';
import { IsString, ValidateIf } from 'class-validator';
export class OtpVerifyDto {
@ApiProperty({
name: 'otp_code',
type: String,
required: true,
example: '2345',
})
@IsString()
@ValidateIf((body) => body.otp_code)
otp_code: string;
}

View File

@ -16,6 +16,7 @@ import { Public } from 'src/core/guards';
import { TransactionEntity } from '../../transaction/domain/entities/transaction.entity';
import { UpdateReconciliationDto } from './dto/reconciliation.dto';
import { RecapReconciliationDto } from './dto/recap.dto';
import { OtpVerifyDto } from './dto/cancel-top-dto';
@ApiTags(`${MODULE_NAME.RECONCILIATION.split('-').join(' ')} - data`)
@Controller(`v1/${MODULE_NAME.RECONCILIATION}`)
@ -40,8 +41,11 @@ export class ReconciliationDataController {
}
@Patch(':id/cancel')
async cancel(@Param('id') dataId: string): Promise<string> {
return await this.orchestrator.cancel(dataId);
async cancel(
@Param('id') dataId: string,
@Body() body: OtpVerifyDto,
): Promise<string> {
return await this.orchestrator.cancel(dataId, body);
}
@Put('/batch-cancel')

Some files were not shown because too many files have changed in this diff Show More