Compare commits
83 Commits
1.6.5-alph
...
developmen
Author | SHA1 | Date |
---|---|---|
|
7bb539db0c | |
|
92b54635d0 | |
|
7be4c26ef2 | |
|
23b3c31810 | |
|
b96d24de1a | |
|
5d3f9d7bff | |
|
831593e743 | |
|
162bd0918f | |
|
13b5838393 | |
|
63bb55b04b | |
|
9d1c240b6b | |
|
83f3377465 | |
|
69c2ee06cf | |
|
42060384aa | |
|
62cfb1f1a8 | |
|
08a35dfdf4 | |
|
8df836ff3e | |
|
822cfe606a | |
|
de43f0f28b | |
|
09b0133bf4 | |
|
a77e6b0381 | |
|
a5da557dd9 | |
|
afad02ba52 | |
|
6636c596f4 | |
|
01fb358875 | |
|
f9dc49f7d5 | |
|
1d9cdfe8e6 | |
|
ccc363f74f | |
|
af1ee2fbee | |
|
ec5229645f | |
|
47d45cb65c | |
|
d6717c9c60 | |
|
d995982203 | |
|
56e475d61f | |
|
3116acd5ab | |
|
068c4ce349 | |
|
79c9139c3c | |
|
d4e8e72af0 | |
|
7dd29c2a70 | |
|
0b5b0ce09b | |
|
e1d3ee7188 | |
|
838670c822 | |
|
34d8882ec3 | |
|
8fb8aac0f9 | |
|
3a0efb00a9 | |
|
737575176e | |
|
f0e8fbddc9 | |
|
d8fa72ba20 | |
|
ab9db39a5f | |
|
7c45a20866 | |
|
7ff0040f9e | |
|
9bbd37ba38 | |
|
b476c92b70 | |
|
dc926d84e4 | |
|
0172eea573 | |
|
464f5cb49e | |
|
1e395ae53f | |
|
2f2fc27965 | |
|
0512c51f8e | |
|
6da2118ab5 | |
|
033ed0046e | |
|
fdbd667b7d | |
|
baeb72fe7d | |
|
4e2ec4d94f | |
|
94fbec0c78 | |
|
e24fee86ba | |
|
16df6945b7 | |
|
8497a5779d | |
|
399ca0bdda | |
|
b8dd2a4e01 | |
|
6a7ab72e12 | |
|
ffc75ba174 | |
|
18afc47030 | |
|
dc1fadbe1f | |
|
a1ed81eec5 | |
|
8192396085 | |
|
3661d9d171 | |
|
d4d605d168 | |
|
10a553ac9d | |
|
d95f8fd6e5 | |
|
9bc2f5fde2 | |
|
0d8ec858eb | |
|
c97399ae8f |
|
@ -59,6 +59,7 @@
|
||||||
"pdfmake": "^0.2.10",
|
"pdfmake": "^0.2.10",
|
||||||
"pg": "^8.11.5",
|
"pg": "^8.11.5",
|
||||||
"plop": "^4.0.1",
|
"plop": "^4.0.1",
|
||||||
|
"qrcode": "^1.5.4",
|
||||||
"reflect-metadata": "^0.2.0",
|
"reflect-metadata": "^0.2.0",
|
||||||
"rxjs": "^7.5.0",
|
"rxjs": "^7.5.0",
|
||||||
"typeorm": "^0.3.20",
|
"typeorm": "^0.3.20",
|
||||||
|
@ -71,6 +72,7 @@
|
||||||
"@types/express": "^4.17.13",
|
"@types/express": "^4.17.13",
|
||||||
"@types/jest": "29.5.12",
|
"@types/jest": "29.5.12",
|
||||||
"@types/node": "^20.12.13",
|
"@types/node": "^20.12.13",
|
||||||
|
"@types/qrcode": "^1.5.5",
|
||||||
"@types/supertest": "^2.0.11",
|
"@types/supertest": "^2.0.11",
|
||||||
"@typescript-eslint/eslint-plugin": "^5.0.0",
|
"@typescript-eslint/eslint-plugin": "^5.0.0",
|
||||||
"@typescript-eslint/parser": "^5.0.0",
|
"@typescript-eslint/parser": "^5.0.0",
|
||||||
|
|
|
@ -105,6 +105,8 @@ import { TimeGroupModel } from './modules/item-related/time-group/data/models/ti
|
||||||
import { OtpVerificationModule } from './modules/configuration/otp-verification/otp-verification.module';
|
import { OtpVerificationModule } from './modules/configuration/otp-verification/otp-verification.module';
|
||||||
import { OtpVerificationModel } from './modules/configuration/otp-verification/data/models/otp-verification.model';
|
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 { 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({
|
@Module({
|
||||||
imports: [
|
imports: [
|
||||||
|
@ -170,6 +172,7 @@ import { OtpVerifierModel } from './modules/configuration/otp-verification/data/
|
||||||
|
|
||||||
// Booking Online
|
// Booking Online
|
||||||
VerificationModel,
|
VerificationModel,
|
||||||
|
RescheduleVerificationModel,
|
||||||
|
|
||||||
OtpVerificationModel,
|
OtpVerificationModel,
|
||||||
OtpVerifierModel,
|
OtpVerifierModel,
|
||||||
|
@ -244,6 +247,8 @@ import { OtpVerifierModel } from './modules/configuration/otp-verification/data/
|
||||||
providers: [
|
providers: [
|
||||||
AuthService,
|
AuthService,
|
||||||
PrivilegeService,
|
PrivilegeService,
|
||||||
|
OtpCheckerGuard,
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* By default all request from client will protect by JWT
|
* By default all request from client will protect by JWT
|
||||||
* if there is some endpoint/function that does'nt require authentication
|
* if there is some endpoint/function that does'nt require authentication
|
||||||
|
|
|
@ -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.');
|
||||||
|
}
|
||||||
|
}
|
|
@ -38,6 +38,14 @@ export class OtpService {
|
||||||
return Object.values(counts).some((count) => count > 2);
|
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 {
|
public generateSecureOTP(): string {
|
||||||
let otp: string;
|
let otp: string;
|
||||||
|
|
||||||
|
@ -46,13 +54,13 @@ export class OtpService {
|
||||||
Math.floor(Math.random() * 10).toString(),
|
Math.floor(Math.random() * 10).toString(),
|
||||||
).join('');
|
).join('');
|
||||||
} while (
|
} while (
|
||||||
|
this.hasNoMatchLength(otp) ||
|
||||||
this.hasSequentialDigits(otp) ||
|
this.hasSequentialDigits(otp) ||
|
||||||
this.hasRepeatedDigits(otp) ||
|
this.hasRepeatedDigits(otp) ||
|
||||||
this.isPalindrome(otp) ||
|
this.isPalindrome(otp) ||
|
||||||
this.hasPartiallyRepeatedDigits(otp) ||
|
this.hasPartiallyRepeatedDigits(otp) ||
|
||||||
otp?.split('')?.length < this.otpLength
|
this.hasStartWithZero(otp)
|
||||||
);
|
);
|
||||||
|
|
||||||
return otp;
|
return otp;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -55,7 +55,7 @@ export class ValidateRelationHelper<Entity> {
|
||||||
const relationColumn =
|
const relationColumn =
|
||||||
data[relation.relation]?.[`${relation.singleQuery[0]}`];
|
data[relation.relation]?.[`${relation.singleQuery[0]}`];
|
||||||
if (
|
if (
|
||||||
!!relationColumn &&
|
// !!relationColumn &&
|
||||||
this.mappingValidator(
|
this.mappingValidator(
|
||||||
relationColumn,
|
relationColumn,
|
||||||
relation.singleQuery[1],
|
relation.singleQuery[1],
|
||||||
|
|
|
@ -31,4 +31,6 @@ export enum MODULE_NAME {
|
||||||
|
|
||||||
TIME_GROUPS = 'time-groups',
|
TIME_GROUPS = 'time-groups',
|
||||||
OTP_VERIFICATIONS = 'otp-verification',
|
OTP_VERIFICATIONS = 'otp-verification',
|
||||||
|
|
||||||
|
OTP_VERIFIER = 'otp-verifier',
|
||||||
}
|
}
|
||||||
|
|
|
@ -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"`);
|
||||||
|
}
|
||||||
|
}
|
|
@ -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"`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
|
@ -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"`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
|
@ -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"`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
|
@ -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"`);
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,17 @@
|
||||||
|
import { MigrationInterface, QueryRunner } from 'typeorm';
|
||||||
|
|
||||||
|
export class RemoveItemNameUnique1750834308368 implements MigrationInterface {
|
||||||
|
name = 'RemoveItemNameUnique1750834308368';
|
||||||
|
|
||||||
|
public async up(queryRunner: QueryRunner): Promise<void> {
|
||||||
|
await queryRunner.query(
|
||||||
|
`ALTER TABLE "items" DROP CONSTRAINT "UQ_213736582899b3599acaade2cd1"`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
public async down(queryRunner: QueryRunner): Promise<void> {
|
||||||
|
await queryRunner.query(
|
||||||
|
`ALTER TABLE "items" ADD CONSTRAINT "UQ_213736582899b3599acaade2cd1" UNIQUE ("name")`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
|
@ -25,6 +25,7 @@ export class VerificationService {
|
||||||
}
|
}
|
||||||
|
|
||||||
async register(data: BookingVerification) {
|
async register(data: BookingVerification) {
|
||||||
|
const isProduction = process.env.NODE_ENV === 'true';
|
||||||
const currentTime = Math.floor(Date.now()); // current time in seconds
|
const currentTime = Math.floor(Date.now()); // current time in seconds
|
||||||
|
|
||||||
// Generate a 4 digit OTP code
|
// Generate a 4 digit OTP code
|
||||||
|
@ -35,6 +36,7 @@ export class VerificationService {
|
||||||
});
|
});
|
||||||
|
|
||||||
if (
|
if (
|
||||||
|
isProduction &&
|
||||||
verification.updated_at &&
|
verification.updated_at &&
|
||||||
currentTime - verification.updated_at < this.expiredTimeRegister
|
currentTime - verification.updated_at < this.expiredTimeRegister
|
||||||
) {
|
) {
|
||||||
|
|
|
@ -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;
|
||||||
|
}
|
|
@ -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;
|
||||||
|
}
|
|
@ -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;
|
||||||
|
}
|
|
@ -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;
|
||||||
|
}
|
||||||
|
}
|
|
@ -5,6 +5,7 @@ import { TransactionType } from 'src/modules/transaction/transaction/constants';
|
||||||
import { CreateTransactionManager } from 'src/modules/transaction/transaction/domain/usecases/managers/create-transaction.manager';
|
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 { 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 { 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';
|
import { v4 as uuidv4 } from 'uuid';
|
||||||
|
|
||||||
export class CreateBookingManager extends CreateTransactionManager {
|
export class CreateBookingManager extends CreateTransactionManager {
|
||||||
|
@ -43,4 +44,21 @@ export class CreateBookingManager extends CreateTransactionManager {
|
||||||
});
|
});
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async afterProcess(): Promise<void> {
|
||||||
|
const whatsapp = new WhatsappService();
|
||||||
|
console.log(`/snap/v4/redirection/${this.data.payment_midtrans_token}`);
|
||||||
|
console.log(this.data.payment_midtrans_url);
|
||||||
|
await whatsapp.bookingRegister(
|
||||||
|
{
|
||||||
|
phone: this.data.customer_phone,
|
||||||
|
code: this.data.invoice_code,
|
||||||
|
name: this.data.customer_name,
|
||||||
|
time: this.data.booking_date,
|
||||||
|
id: this.data.id,
|
||||||
|
},
|
||||||
|
this.data.payment_total,
|
||||||
|
`snap/v4/redirection/${this.data.payment_midtrans_token}`,
|
||||||
|
);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -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;
|
||||||
|
}
|
||||||
|
}
|
|
@ -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,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
|
@ -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;
|
||||||
|
}
|
|
@ -1,19 +1,19 @@
|
||||||
import { Controller, Get, Query } from '@nestjs/common';
|
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 { Public } from 'src/core/guards';
|
||||||
import { PaginationResponse } from 'src/core/response/domain/ok-response.interface';
|
import { PaginationResponse } from 'src/core/response/domain/ok-response.interface';
|
||||||
import { TABLE_NAME } from 'src/core/strings/constants/table.constants';
|
import { TABLE_NAME } from 'src/core/strings/constants/table.constants';
|
||||||
import { ItemReadService } from 'src/modules/item-related/item/data/services/item-read.service';
|
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 { 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 { FilterItemDto } from 'src/modules/item-related/item/infrastructure/dto/filter-item.dto';
|
||||||
|
import { BookingItemManager } from '../domain/usecases/managers/booking-item.manager';
|
||||||
|
|
||||||
@ApiTags('Booking Item')
|
@ApiTags('Booking Item')
|
||||||
@Controller('v1/booking-item')
|
@Controller('v1/booking-item')
|
||||||
@Public(true)
|
@Public(true)
|
||||||
export class ItemController {
|
export class ItemController {
|
||||||
constructor(
|
constructor(
|
||||||
private indexManager: IndexItemManager,
|
private indexManager: BookingItemManager,
|
||||||
private serviceData: ItemReadService,
|
private serviceData: ItemReadService,
|
||||||
) {}
|
) {}
|
||||||
|
|
||||||
|
@ -21,7 +21,9 @@ export class ItemController {
|
||||||
async index(
|
async index(
|
||||||
@Query() params: FilterItemDto,
|
@Query() params: FilterItemDto,
|
||||||
): Promise<PaginationResponse<ItemEntity>> {
|
): Promise<PaginationResponse<ItemEntity>> {
|
||||||
|
params.limit = 1000;
|
||||||
params.show_to_booking = true;
|
params.show_to_booking = true;
|
||||||
|
params.all_item = true;
|
||||||
this.indexManager.setFilterParam(params);
|
this.indexManager.setFilterParam(params);
|
||||||
this.indexManager.setService(this.serviceData, TABLE_NAME.ITEM);
|
this.indexManager.setService(this.serviceData, TABLE_NAME.ITEM);
|
||||||
await this.indexManager.execute();
|
await this.indexManager.execute();
|
||||||
|
|
|
@ -1,4 +1,12 @@
|
||||||
import { Body, Controller, Get, Param, Post } from '@nestjs/common';
|
import {
|
||||||
|
Body,
|
||||||
|
Controller,
|
||||||
|
Get,
|
||||||
|
Param,
|
||||||
|
Post,
|
||||||
|
Res,
|
||||||
|
UnprocessableEntityException,
|
||||||
|
} from '@nestjs/common';
|
||||||
import { ApiTags } from '@nestjs/swagger';
|
import { ApiTags } from '@nestjs/swagger';
|
||||||
import { Public } from 'src/core/guards';
|
import { Public } from 'src/core/guards';
|
||||||
import { TransactionDto } from './dto/booking-order.dto';
|
import { TransactionDto } from './dto/booking-order.dto';
|
||||||
|
@ -7,6 +15,18 @@ import { TransactionDataService } from 'src/modules/transaction/transaction/data
|
||||||
import { TABLE_NAME } from 'src/core/strings/constants/table.constants';
|
import { TABLE_NAME } from 'src/core/strings/constants/table.constants';
|
||||||
import { MidtransService } from 'src/modules/configuration/midtrans/data/services/midtrans.service';
|
import { MidtransService } from 'src/modules/configuration/midtrans/data/services/midtrans.service';
|
||||||
import { CreateBookingManager } from '../domain/usecases/managers/create-booking.manager';
|
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')
|
@ApiTags('Booking Order')
|
||||||
@Controller('v1/booking')
|
@Controller('v1/booking')
|
||||||
|
@ -16,6 +36,8 @@ export class BookingOrderController {
|
||||||
private createBooking: CreateBookingManager,
|
private createBooking: CreateBookingManager,
|
||||||
private serviceData: TransactionDataService,
|
private serviceData: TransactionDataService,
|
||||||
private midtransService: MidtransService,
|
private midtransService: MidtransService,
|
||||||
|
private rescheduleVerification: RescheduleVerificationManager,
|
||||||
|
private rescheduleManager: RescheduleManager,
|
||||||
) {}
|
) {}
|
||||||
|
|
||||||
@Post()
|
@Post()
|
||||||
|
@ -47,14 +69,80 @@ export class BookingOrderController {
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@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')
|
@Get(':id')
|
||||||
async get(@Param('id') transactionId: string) {
|
async get(@Param('id') transactionId: string) {
|
||||||
const data = await this.serviceData.getOneByOptions({
|
const data = await this.serviceData.getOneByOptions({
|
||||||
relations: ['items'],
|
relations: [
|
||||||
|
'items',
|
||||||
|
'parent_transaction',
|
||||||
|
'items.item',
|
||||||
|
'items.item.time_group',
|
||||||
|
],
|
||||||
where: { id: transactionId },
|
where: { id: transactionId },
|
||||||
});
|
});
|
||||||
|
|
||||||
const {
|
const {
|
||||||
|
parent_id,
|
||||||
customer_name,
|
customer_name,
|
||||||
customer_phone,
|
customer_phone,
|
||||||
booking_date,
|
booking_date,
|
||||||
|
@ -62,9 +150,30 @@ export class BookingOrderController {
|
||||||
status,
|
status,
|
||||||
id,
|
id,
|
||||||
items,
|
items,
|
||||||
|
parent_transaction,
|
||||||
} = data;
|
} = data;
|
||||||
|
|
||||||
|
let timeGroup = null;
|
||||||
|
|
||||||
const usageItems = items.map((item) => {
|
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 {
|
const {
|
||||||
id,
|
id,
|
||||||
item_id,
|
item_id,
|
||||||
|
@ -96,6 +205,20 @@ export class BookingOrderController {
|
||||||
maskedCustomerPhone = '*'.repeat(customer_phone.length - 4) + last4;
|
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 {
|
return {
|
||||||
customer_name,
|
customer_name,
|
||||||
customer_phone: maskedCustomerPhone,
|
customer_phone: maskedCustomerPhone,
|
||||||
|
@ -103,7 +226,49 @@ export class BookingOrderController {
|
||||||
invoice_code,
|
invoice_code,
|
||||||
status,
|
status,
|
||||||
id,
|
id,
|
||||||
|
is_reschedule: !!parent_id,
|
||||||
items: usageItems,
|
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',
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -11,16 +11,28 @@ import { BookingOrderController } from './infrastructure/order.controller';
|
||||||
import { CreateBookingManager } from './domain/usecases/managers/create-booking.manager';
|
import { CreateBookingManager } from './domain/usecases/managers/create-booking.manager';
|
||||||
import { MidtransModule } from 'src/modules/configuration/midtrans/midtrans.module';
|
import { MidtransModule } from 'src/modules/configuration/midtrans/midtrans.module';
|
||||||
import { CqrsModule } from '@nestjs/cqrs';
|
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({
|
@Module({
|
||||||
imports: [
|
imports: [
|
||||||
ConfigModule.forRoot(),
|
ConfigModule.forRoot(),
|
||||||
TypeOrmModule.forFeature([ItemModel], CONNECTION_NAME.DEFAULT),
|
TypeOrmModule.forFeature(
|
||||||
|
[ItemModel, RescheduleVerificationModel],
|
||||||
|
CONNECTION_NAME.DEFAULT,
|
||||||
|
),
|
||||||
ItemModule,
|
ItemModule,
|
||||||
TransactionModule,
|
TransactionModule,
|
||||||
MidtransModule,
|
MidtransModule,
|
||||||
CqrsModule,
|
CqrsModule,
|
||||||
],
|
],
|
||||||
controllers: [ItemController, BookingOrderController],
|
controllers: [ItemController, BookingOrderController],
|
||||||
providers: [CreateBookingManager],
|
providers: [
|
||||||
|
CreateBookingManager,
|
||||||
|
RescheduleVerificationManager,
|
||||||
|
RescheduleManager,
|
||||||
|
BookingItemManager,
|
||||||
|
],
|
||||||
})
|
})
|
||||||
export class BookingOrderModule {}
|
export class BookingOrderModule {}
|
||||||
|
|
|
@ -3,4 +3,5 @@ export const DatabaseListen = [
|
||||||
'vip_code',
|
'vip_code',
|
||||||
'pos_activity',
|
'pos_activity',
|
||||||
'pos_cash_activity',
|
'pos_cash_activity',
|
||||||
|
'time_groups',
|
||||||
];
|
];
|
||||||
|
|
|
@ -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 { SeasonPeriodModel } from 'src/modules/season-related/season-period/data/models/season-period.model';
|
||||||
import { TransactionDemographyModel } from 'src/modules/transaction/transaction/data/models/transaction-demography.model';
|
import { TransactionDemographyModel } from 'src/modules/transaction/transaction/data/models/transaction-demography.model';
|
||||||
import { UserLoginModel } from 'src/modules/user-related/user/data/models/user-login.model';
|
import { UserLoginModel } from 'src/modules/user-related/user/data/models/user-login.model';
|
||||||
|
import {
|
||||||
|
TimeGroupDeletedHandler,
|
||||||
|
TimeGroupUpdatedHandler,
|
||||||
|
} from './domain/managers/time-group.handle';
|
||||||
|
|
||||||
@Module({
|
@Module({
|
||||||
imports: [
|
imports: [
|
||||||
|
@ -83,6 +87,10 @@ import { UserLoginModel } from 'src/modules/user-related/user/data/models/user-l
|
||||||
VipCodeCreatedHandler,
|
VipCodeCreatedHandler,
|
||||||
VipCategoryDeletedHandler,
|
VipCategoryDeletedHandler,
|
||||||
VipCategoryUpdatedHandler,
|
VipCategoryUpdatedHandler,
|
||||||
|
|
||||||
|
TimeGroupDeletedHandler,
|
||||||
|
TimeGroupUpdatedHandler,
|
||||||
|
|
||||||
SeasonPeriodDeletedHandler,
|
SeasonPeriodDeletedHandler,
|
||||||
SeasonPeriodUpdatedHandler,
|
SeasonPeriodUpdatedHandler,
|
||||||
ItemUpdatedHandler,
|
ItemUpdatedHandler,
|
||||||
|
|
|
@ -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',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
|
@ -10,7 +10,7 @@ import { TypeOrmModule } from '@nestjs/typeorm';
|
||||||
import { CONNECTION_NAME } from 'src/core/strings/constants/base.constants';
|
import { CONNECTION_NAME } from 'src/core/strings/constants/base.constants';
|
||||||
import { TransactionItemModel } from 'src/modules/transaction/transaction/data/models/transaction-item.model';
|
import { TransactionItemModel } from 'src/modules/transaction/transaction/data/models/transaction-item.model';
|
||||||
import { TransactionTaxModel } from 'src/modules/transaction/transaction/data/models/transaction-tax.model';
|
import { TransactionTaxModel } from 'src/modules/transaction/transaction/data/models/transaction-tax.model';
|
||||||
|
import { CouchModule } from 'src/modules/configuration/couch/couch.module';
|
||||||
@Module({
|
@Module({
|
||||||
imports: [
|
imports: [
|
||||||
ConfigModule.forRoot(),
|
ConfigModule.forRoot(),
|
||||||
|
@ -19,6 +19,7 @@ import { TransactionTaxModel } from 'src/modules/transaction/transaction/data/mo
|
||||||
CONNECTION_NAME.DEFAULT,
|
CONNECTION_NAME.DEFAULT,
|
||||||
),
|
),
|
||||||
CqrsModule,
|
CqrsModule,
|
||||||
|
CouchModule,
|
||||||
],
|
],
|
||||||
controllers: [GoogleCalendarController],
|
controllers: [GoogleCalendarController],
|
||||||
providers: [
|
providers: [
|
||||||
|
|
|
@ -10,7 +10,7 @@ import { TransactionDataService } from 'src/modules/transaction/transaction/data
|
||||||
import { PaymentTransactionHandler } from './domain/handlers/payment-transaction.handler';
|
import { PaymentTransactionHandler } from './domain/handlers/payment-transaction.handler';
|
||||||
import { MailTemplateController } from './infrastructure/mail.controller';
|
import { MailTemplateController } from './infrastructure/mail.controller';
|
||||||
import { PdfMakeManager } from '../export/domain/managers/pdf-make.manager';
|
import { PdfMakeManager } from '../export/domain/managers/pdf-make.manager';
|
||||||
|
import { CouchModule } from '../couch/couch.module';
|
||||||
@Module({
|
@Module({
|
||||||
imports: [
|
imports: [
|
||||||
ConfigModule.forRoot(),
|
ConfigModule.forRoot(),
|
||||||
|
@ -19,6 +19,7 @@ import { PdfMakeManager } from '../export/domain/managers/pdf-make.manager';
|
||||||
CONNECTION_NAME.DEFAULT,
|
CONNECTION_NAME.DEFAULT,
|
||||||
),
|
),
|
||||||
CqrsModule,
|
CqrsModule,
|
||||||
|
CouchModule,
|
||||||
],
|
],
|
||||||
controllers: [MailTemplateController],
|
controllers: [MailTemplateController],
|
||||||
providers: [
|
providers: [
|
||||||
|
|
|
@ -1,5 +1,8 @@
|
||||||
import { TABLE_NAME } from 'src/core/strings/constants/table.constants';
|
import { TABLE_NAME } from 'src/core/strings/constants/table.constants';
|
||||||
import { OtpVerifierEntity } from '../../domain/entities/otp-verification.entity';
|
import {
|
||||||
|
OTP_ACTION_TYPE,
|
||||||
|
OtpVerifierEntity,
|
||||||
|
} from '../../domain/entities/otp-verification.entity';
|
||||||
import { Column, Entity } from 'typeorm';
|
import { Column, Entity } from 'typeorm';
|
||||||
import { BaseModel } from 'src/core/modules/data/model/base.model';
|
import { BaseModel } from 'src/core/modules/data/model/base.model';
|
||||||
|
|
||||||
|
@ -13,4 +16,10 @@ export class OtpVerifierModel
|
||||||
|
|
||||||
@Column({ type: 'varchar', nullable: false })
|
@Column({ type: 'varchar', nullable: false })
|
||||||
phone_number: string;
|
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;
|
||||||
}
|
}
|
||||||
|
|
|
@ -3,6 +3,7 @@ import { InjectRepository } from '@nestjs/typeorm';
|
||||||
import { Repository } from 'typeorm';
|
import { Repository } from 'typeorm';
|
||||||
import { OtpVerificationModel } from '../models/otp-verification.model';
|
import { OtpVerificationModel } from '../models/otp-verification.model';
|
||||||
import {
|
import {
|
||||||
|
OTP_ACTION_TYPE,
|
||||||
OtpRequestEntity,
|
OtpRequestEntity,
|
||||||
OtpVerificationEntity,
|
OtpVerificationEntity,
|
||||||
OtpVerifierEntity,
|
OtpVerifierEntity,
|
||||||
|
@ -37,14 +38,81 @@ export class OtpVerificationService {
|
||||||
return moment().valueOf(); // epoch millis verification time (now)
|
return moment().valueOf(); // epoch millis verification time (now)
|
||||||
}
|
}
|
||||||
|
|
||||||
async requestOTP(payload: OtpRequestEntity) {
|
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 otpService = new OtpService({ length: 4 });
|
||||||
const otpCode = otpService.generateSecureOTP();
|
const otpCode = otpService.generateSecureOTP();
|
||||||
const dateNow = this.generateTimestamp();
|
const dateNow = this.generateTimestamp();
|
||||||
const expiredAt = this.generateOtpExpiration();
|
const expiredAt = this.generateOtpExpiration();
|
||||||
|
const userRequest = req?.user;
|
||||||
//TODO implementation from auth
|
|
||||||
const creator = { id: null, name: null };
|
|
||||||
|
|
||||||
const newOtp: OtpVerificationEntity = {
|
const newOtp: OtpVerificationEntity = {
|
||||||
otp_code: otpCode,
|
otp_code: otpCode,
|
||||||
|
@ -56,13 +124,13 @@ export class OtpVerificationService {
|
||||||
is_replaced: false,
|
is_replaced: false,
|
||||||
expired_at: expiredAt,
|
expired_at: expiredAt,
|
||||||
|
|
||||||
creator_id: creator.id,
|
creator_id: userRequest?.id,
|
||||||
creator_name: creator.name,
|
creator_name: userRequest?.name,
|
||||||
created_at: dateNow,
|
created_at: dateNow,
|
||||||
verified_at: null,
|
verified_at: null,
|
||||||
|
|
||||||
editor_id: creator.id,
|
editor_id: userRequest?.id,
|
||||||
editor_name: creator.name,
|
editor_name: userRequest?.name,
|
||||||
updated_at: dateNow,
|
updated_at: dateNow,
|
||||||
};
|
};
|
||||||
|
|
||||||
|
@ -74,7 +142,9 @@ export class OtpVerificationService {
|
||||||
const createdAtMoment = moment(Number(activeOTP.created_at));
|
const createdAtMoment = moment(Number(activeOTP.created_at));
|
||||||
const nowMoment = moment(Number(dateNow));
|
const nowMoment = moment(Number(dateNow));
|
||||||
const diffSeconds = nowMoment.diff(createdAtMoment, 'seconds');
|
const diffSeconds = nowMoment.diff(createdAtMoment, 'seconds');
|
||||||
if (diffSeconds < 60) {
|
const isProduction = process.env.NODE_ENV === 'true';
|
||||||
|
|
||||||
|
if (diffSeconds < 60 && isProduction) {
|
||||||
throw new BadRequestException(
|
throw new BadRequestException(
|
||||||
'An active OTP request was made recently. Please try again later.',
|
'An active OTP request was made recently. Please try again later.',
|
||||||
);
|
);
|
||||||
|
@ -89,13 +159,15 @@ export class OtpVerificationService {
|
||||||
|
|
||||||
// save otp to database
|
// save otp to database
|
||||||
await this.otpVerificationRepo.save(newOtp);
|
await this.otpVerificationRepo.save(newOtp);
|
||||||
const verifiers: OtpVerifierEntity[] = await this.otpVerifierRepo.find();
|
const verifiers: OtpVerifierEntity[] = await this.getVerifier([
|
||||||
|
payload.action_type,
|
||||||
|
]);
|
||||||
const notificationService = new WhatsappService();
|
const notificationService = new WhatsappService();
|
||||||
|
|
||||||
verifiers.map((v) => {
|
verifiers?.map((v) => {
|
||||||
notificationService.sendOtpNotification({
|
notificationService.sendTemplateMessage({
|
||||||
phone: v.phone_number,
|
phone: v.phone_number,
|
||||||
code: otpCode,
|
templateMsg: this.generateOTPMsgTemplate({ userRequest, newOtp }),
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
@ -106,7 +178,8 @@ export class OtpVerificationService {
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
async verifyOTP(payload: OtpVerifyEntity) {
|
async verifyOTP(payload: OtpVerifyEntity, req: any) {
|
||||||
|
const userRequest = req?.user;
|
||||||
const { otp_code, action_type, target_id, reference, source } = payload;
|
const { otp_code, action_type, target_id, reference, source } = payload;
|
||||||
const dateNow = this.generateTimestamp();
|
const dateNow = this.generateTimestamp();
|
||||||
|
|
||||||
|
@ -116,10 +189,13 @@ export class OtpVerificationService {
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
let otp: any;
|
||||||
|
|
||||||
// Build a where condition with OR between target_id and reference
|
// Build a where condition with OR between target_id and reference
|
||||||
const otp = await this.otpVerificationRepo.findOne({
|
|
||||||
where: [
|
if (target_id) {
|
||||||
{
|
otp = await this.otpVerificationRepo.findOne({
|
||||||
|
where: {
|
||||||
otp_code,
|
otp_code,
|
||||||
action_type,
|
action_type,
|
||||||
target_id,
|
target_id,
|
||||||
|
@ -127,7 +203,10 @@ export class OtpVerificationService {
|
||||||
is_used: false,
|
is_used: false,
|
||||||
is_replaced: false,
|
is_replaced: false,
|
||||||
},
|
},
|
||||||
{
|
});
|
||||||
|
} else if (reference) {
|
||||||
|
otp = await this.otpVerificationRepo.findOne({
|
||||||
|
where: {
|
||||||
otp_code,
|
otp_code,
|
||||||
action_type,
|
action_type,
|
||||||
reference,
|
reference,
|
||||||
|
@ -135,8 +214,8 @@ export class OtpVerificationService {
|
||||||
is_used: false,
|
is_used: false,
|
||||||
is_replaced: false,
|
is_replaced: false,
|
||||||
},
|
},
|
||||||
],
|
|
||||||
});
|
});
|
||||||
|
}
|
||||||
|
|
||||||
if (!otp) {
|
if (!otp) {
|
||||||
throw new BadRequestException('Invalid or expired OTP.');
|
throw new BadRequestException('Invalid or expired OTP.');
|
||||||
|
@ -146,6 +225,9 @@ export class OtpVerificationService {
|
||||||
|
|
||||||
otp.is_used = true;
|
otp.is_used = true;
|
||||||
otp.verified_at = dateNow;
|
otp.verified_at = dateNow;
|
||||||
|
otp.editor_id = userRequest?.id;
|
||||||
|
otp.editor_name = userRequest?.name;
|
||||||
|
otp.updated_at = dateNow;
|
||||||
|
|
||||||
// update otp to database
|
// update otp to database
|
||||||
await this.otpVerificationRepo.save(otp);
|
await this.otpVerificationRepo.save(otp);
|
||||||
|
@ -171,4 +253,14 @@ export class OtpVerificationService {
|
||||||
)
|
)
|
||||||
.getOne();
|
.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 ?? [];
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -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,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
|
@ -4,6 +4,14 @@ export enum OTP_ACTION_TYPE {
|
||||||
CREATE_DISCOUNT = 'CREATE_DISCOUNT',
|
CREATE_DISCOUNT = 'CREATE_DISCOUNT',
|
||||||
CANCEL_TRANSACTION = 'CANCEL_TRANSACTION',
|
CANCEL_TRANSACTION = 'CANCEL_TRANSACTION',
|
||||||
REJECT_RECONCILIATION = 'REJECT_RECONCILIATION',
|
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 {
|
export enum OTP_SOURCE {
|
||||||
|
@ -37,4 +45,6 @@ export interface OtpVerifyEntity extends OtpRequestEntity {
|
||||||
export interface OtpVerifierEntity {
|
export interface OtpVerifierEntity {
|
||||||
name: string;
|
name: string;
|
||||||
phone_number: string;
|
phone_number: string;
|
||||||
|
is_all_action?: boolean;
|
||||||
|
action_types?: OTP_ACTION_TYPE[] | null;
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,4 +1,13 @@
|
||||||
import { IsNotEmpty, IsString, ValidateIf } from 'class-validator';
|
import {
|
||||||
|
IsArray,
|
||||||
|
IsBoolean,
|
||||||
|
IsEnum,
|
||||||
|
IsNotEmpty,
|
||||||
|
IsOptional,
|
||||||
|
IsPhoneNumber,
|
||||||
|
IsString,
|
||||||
|
ValidateIf,
|
||||||
|
} from 'class-validator';
|
||||||
import {
|
import {
|
||||||
OTP_ACTION_TYPE,
|
OTP_ACTION_TYPE,
|
||||||
OTP_SOURCE,
|
OTP_SOURCE,
|
||||||
|
@ -6,6 +15,7 @@ import {
|
||||||
OtpVerifyEntity,
|
OtpVerifyEntity,
|
||||||
} from '../../domain/entities/otp-verification.entity';
|
} from '../../domain/entities/otp-verification.entity';
|
||||||
import { ApiProperty } from '@nestjs/swagger';
|
import { ApiProperty } from '@nestjs/swagger';
|
||||||
|
import { Type } from 'class-transformer';
|
||||||
|
|
||||||
export class OtpRequestDto implements OtpRequestEntity {
|
export class OtpRequestDto implements OtpRequestEntity {
|
||||||
@ApiProperty({
|
@ApiProperty({
|
||||||
|
@ -53,3 +63,50 @@ export class OtpVerifyDto extends OtpRequestDto implements OtpVerifyEntity {
|
||||||
@IsNotEmpty()
|
@IsNotEmpty()
|
||||||
otp_code: string;
|
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[];
|
||||||
|
}
|
||||||
|
|
|
@ -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',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
|
@ -1,11 +1,24 @@
|
||||||
import { Body, Controller, Get, Param, Post } from '@nestjs/common';
|
import {
|
||||||
import { ApiTags } from '@nestjs/swagger';
|
Body,
|
||||||
import { Public } from 'src/core/guards';
|
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 { MODULE_NAME } from 'src/core/strings/constants/module.constants';
|
||||||
import { OtpVerificationService } from '../data/services/otp-verification.service';
|
import { OtpVerificationService } from '../data/services/otp-verification.service';
|
||||||
import { OtpRequestDto, OtpVerifyDto } from './dto/otp-verification.dto';
|
import {
|
||||||
|
OtpRequestDto,
|
||||||
|
OtpVerifierCreateDto,
|
||||||
|
OtpVerifyDto,
|
||||||
|
} from './dto/otp-verification.dto';
|
||||||
|
import { OtpAuthGuard } from './guards/otp-auth.guard';
|
||||||
|
import { OtpVerifierService } from '../data/services/otp-verifier.service';
|
||||||
|
|
||||||
//TODO implementation auth
|
|
||||||
@ApiTags(`${MODULE_NAME.OTP_VERIFICATIONS.split('-').join(' ')} - data`)
|
@ApiTags(`${MODULE_NAME.OTP_VERIFICATIONS.split('-').join(' ')} - data`)
|
||||||
@Controller(`v1/${MODULE_NAME.OTP_VERIFICATIONS}`)
|
@Controller(`v1/${MODULE_NAME.OTP_VERIFICATIONS}`)
|
||||||
@Public()
|
@Public()
|
||||||
|
@ -15,13 +28,15 @@ export class OtpVerificationController {
|
||||||
) {}
|
) {}
|
||||||
|
|
||||||
@Post('request')
|
@Post('request')
|
||||||
async request(@Body() body: OtpRequestDto) {
|
@UseGuards(OtpAuthGuard)
|
||||||
return await this.otpVerificationService.requestOTP(body);
|
async request(@Body() body: OtpRequestDto, @Req() req) {
|
||||||
|
return await this.otpVerificationService.requestOTP(body, req);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Post('verify')
|
@Post('verify')
|
||||||
async verify(@Body() body: OtpVerifyDto) {
|
@UseGuards(OtpAuthGuard)
|
||||||
return await this.otpVerificationService.verifyOTP(body);
|
async verify(@Body() body: OtpVerifyDto, @Req() req) {
|
||||||
|
return await this.otpVerificationService.verifyOTP(body, req);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Get(':ref_or_target_id')
|
@Get(':ref_or_target_id')
|
||||||
|
@ -29,3 +44,17 @@ export class OtpVerificationController {
|
||||||
return this.otpVerificationService.getActiveOtp(ref_or_target_id);
|
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);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
|
@ -4,18 +4,34 @@ import { ConfigModule } from '@nestjs/config';
|
||||||
import { Module } from '@nestjs/common';
|
import { Module } from '@nestjs/common';
|
||||||
import { TypeOrmModule } from '@nestjs/typeorm';
|
import { TypeOrmModule } from '@nestjs/typeorm';
|
||||||
import { OtpVerificationModel } from './data/models/otp-verification.model';
|
import { OtpVerificationModel } from './data/models/otp-verification.model';
|
||||||
import { OtpVerificationController } from './infrastructure/otp-verification-data.controller';
|
import {
|
||||||
|
OtpVerificationController,
|
||||||
|
OtpVerifierController,
|
||||||
|
} from './infrastructure/otp-verification-data.controller';
|
||||||
import { OtpVerificationService } from './data/services/otp-verification.service';
|
import { OtpVerificationService } from './data/services/otp-verification.service';
|
||||||
import { OtpVerifierModel } from './data/models/otp-verifier.model';
|
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({
|
@Module({
|
||||||
imports: [
|
imports: [
|
||||||
ConfigModule.forRoot(),
|
ConfigModule.forRoot(),
|
||||||
|
|
||||||
TypeOrmModule.forFeature(
|
TypeOrmModule.forFeature(
|
||||||
[OtpVerificationModel, OtpVerifierModel],
|
[OtpVerificationModel, OtpVerifierModel],
|
||||||
CONNECTION_NAME.DEFAULT,
|
CONNECTION_NAME.DEFAULT,
|
||||||
),
|
),
|
||||||
|
|
||||||
|
JwtModule.register({
|
||||||
|
secret: JWT_SECRET,
|
||||||
|
signOptions: { expiresIn: JWT_EXPIRED },
|
||||||
|
}),
|
||||||
],
|
],
|
||||||
controllers: [OtpVerificationController],
|
controllers: [OtpVerificationController, OtpVerifierController],
|
||||||
providers: [OtpVerificationService],
|
providers: [OtpAuthGuard, OtpVerificationService, OtpVerifierService],
|
||||||
})
|
})
|
||||||
export class OtpVerificationModule {}
|
export class OtpVerificationModule {}
|
||||||
|
|
|
@ -5,3 +5,8 @@ export enum ItemType {
|
||||||
FREE_GIFT = 'free gift',
|
FREE_GIFT = 'free gift',
|
||||||
OTHER = 'other',
|
OTHER = 'other',
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export enum UsageType {
|
||||||
|
ONE_TIME = 'one_time',
|
||||||
|
MULTIPLE = 'multiple',
|
||||||
|
}
|
||||||
|
|
|
@ -2,7 +2,7 @@ import { TABLE_NAME } from 'src/core/strings/constants/table.constants';
|
||||||
import { ItemQueueEntity } from '../../domain/entities/item-queue.entity';
|
import { ItemQueueEntity } from '../../domain/entities/item-queue.entity';
|
||||||
import { Column, Entity, OneToMany } from 'typeorm';
|
import { Column, Entity, OneToMany } from 'typeorm';
|
||||||
import { BaseStatusModel } from 'src/core/modules/data/model/base-status.model';
|
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';
|
import { ItemModel } from 'src/modules/item-related/item/data/models/item.model';
|
||||||
|
|
||||||
@Entity(TABLE_NAME.ITEM_QUEUE)
|
@Entity(TABLE_NAME.ITEM_QUEUE)
|
||||||
|
@ -29,6 +29,13 @@ export class ItemQueueModel
|
||||||
})
|
})
|
||||||
item_type: ItemType;
|
item_type: ItemType;
|
||||||
|
|
||||||
|
@Column('enum', {
|
||||||
|
name: 'usage_type',
|
||||||
|
enum: UsageType,
|
||||||
|
default: UsageType.ONE_TIME,
|
||||||
|
})
|
||||||
|
usage_type: UsageType;
|
||||||
|
|
||||||
@OneToMany(() => ItemModel, (model) => model.item_queue, {
|
@OneToMany(() => ItemModel, (model) => model.item_queue, {
|
||||||
onUpdate: 'CASCADE',
|
onUpdate: 'CASCADE',
|
||||||
})
|
})
|
||||||
|
|
|
@ -1,5 +1,5 @@
|
||||||
import { BaseStatusEntity } from 'src/core/modules/domain/entities/base-status.entity';
|
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';
|
import { ItemEntity } from 'src/modules/item-related/item/domain/entities/item.entity';
|
||||||
|
|
||||||
export interface ItemQueueEntity extends BaseStatusEntity {
|
export interface ItemQueueEntity extends BaseStatusEntity {
|
||||||
|
@ -11,4 +11,5 @@ export interface ItemQueueEntity extends BaseStatusEntity {
|
||||||
items: ItemEntity[];
|
items: ItemEntity[];
|
||||||
use_notification?: boolean;
|
use_notification?: boolean;
|
||||||
requiring_notification?: boolean;
|
requiring_notification?: boolean;
|
||||||
|
usage_type?: UsageType;
|
||||||
}
|
}
|
||||||
|
|
|
@ -40,6 +40,7 @@ export class DetailItemQueueManager extends BaseDetailManager<ItemQueueEntity> {
|
||||||
`${this.tableName}.call_preparation`,
|
`${this.tableName}.call_preparation`,
|
||||||
`${this.tableName}.use_notification`,
|
`${this.tableName}.use_notification`,
|
||||||
`${this.tableName}.requiring_notification`,
|
`${this.tableName}.requiring_notification`,
|
||||||
|
`${this.tableName}.usage_type`,
|
||||||
|
|
||||||
`items.id`,
|
`items.id`,
|
||||||
`items.created_at`,
|
`items.created_at`,
|
||||||
|
|
|
@ -43,7 +43,7 @@ export class IndexItemQueueManager extends BaseIndexManager<ItemQueueEntity> {
|
||||||
`${this.tableName}.call_preparation`,
|
`${this.tableName}.call_preparation`,
|
||||||
`${this.tableName}.use_notification`,
|
`${this.tableName}.use_notification`,
|
||||||
`${this.tableName}.requiring_notification`,
|
`${this.tableName}.requiring_notification`,
|
||||||
|
`${this.tableName}.usage_type`,
|
||||||
`items.id`,
|
`items.id`,
|
||||||
`items.created_at`,
|
`items.created_at`,
|
||||||
`items.status`,
|
`items.status`,
|
||||||
|
|
|
@ -18,15 +18,19 @@ import { ItemRateModel } from 'src/modules/item-related/item-rate/data/models/it
|
||||||
import { GateModel } from 'src/modules/web-information/gate/data/models/gate.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 { 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 { 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)
|
@Entity(TABLE_NAME.ITEM)
|
||||||
export class ItemModel
|
export class ItemModel
|
||||||
extends BaseStatusModel<ItemEntity>
|
extends BaseStatusModel<ItemEntity>
|
||||||
implements ItemEntity
|
implements ItemEntity
|
||||||
{
|
{
|
||||||
@Column('varchar', { name: 'name', unique: true })
|
@Column('varchar', { name: 'name' })
|
||||||
name: string;
|
name: string;
|
||||||
|
|
||||||
|
@Column('text', { name: 'booking_description', nullable: true })
|
||||||
|
booking_description: string;
|
||||||
|
|
||||||
@Column('varchar', { name: 'image_url', nullable: true })
|
@Column('varchar', { name: 'image_url', nullable: true })
|
||||||
image_url: string;
|
image_url: string;
|
||||||
|
|
||||||
|
@ -40,6 +44,13 @@ export class ItemModel
|
||||||
})
|
})
|
||||||
item_type: ItemType;
|
item_type: ItemType;
|
||||||
|
|
||||||
|
@Column('enum', {
|
||||||
|
name: 'usage_type',
|
||||||
|
enum: UsageType,
|
||||||
|
default: UsageType.ONE_TIME,
|
||||||
|
})
|
||||||
|
usage_type: UsageType;
|
||||||
|
|
||||||
@Column('bigint', { name: 'hpp', nullable: true })
|
@Column('bigint', { name: 'hpp', nullable: true })
|
||||||
hpp: number;
|
hpp: number;
|
||||||
|
|
||||||
|
|
|
@ -1,7 +1,8 @@
|
||||||
import { BaseStatusEntity } from 'src/core/modules/domain/entities/base-status.entity';
|
import { BaseStatusEntity } from 'src/core/modules/domain/entities/base-status.entity';
|
||||||
import { ItemType } from 'src/modules/item-related/item-category/constants';
|
import { ItemType } from 'src/modules/item-related/item-category/constants';
|
||||||
import { LimitType } from '../../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 {
|
export interface ItemEntity extends BaseStatusEntity {
|
||||||
name: string;
|
name: string;
|
||||||
item_type: ItemType;
|
item_type: ItemType;
|
||||||
|
@ -18,4 +19,8 @@ export interface ItemEntity extends BaseStatusEntity {
|
||||||
use_queue: boolean;
|
use_queue: boolean;
|
||||||
show_to_booking: boolean;
|
show_to_booking: boolean;
|
||||||
breakdown_bundling?: boolean;
|
breakdown_bundling?: boolean;
|
||||||
|
booking_description?: string;
|
||||||
|
usage_type?: UsageType;
|
||||||
|
|
||||||
|
item_rates?: ItemRateEntity[] | any[];
|
||||||
}
|
}
|
||||||
|
|
|
@ -8,6 +8,7 @@ import { ItemEntity } from '../../entities/item.entity';
|
||||||
import { ItemModel } from '../../../data/models/item.model';
|
import { ItemModel } from '../../../data/models/item.model';
|
||||||
import { BaseCreateManager } from 'src/core/modules/domain/usecase/managers/base-create.manager';
|
import { BaseCreateManager } from 'src/core/modules/domain/usecase/managers/base-create.manager';
|
||||||
import { ItemCreatedEvent } from '../../entities/event/item-created.event';
|
import { ItemCreatedEvent } from '../../entities/event/item-created.event';
|
||||||
|
import { STATUS } from 'src/core/strings/constants/base.constants';
|
||||||
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
export class CreateItemManager extends BaseCreateManager<ItemEntity> {
|
export class CreateItemManager extends BaseCreateManager<ItemEntity> {
|
||||||
|
@ -29,11 +30,37 @@ export class CreateItemManager extends BaseCreateManager<ItemEntity> {
|
||||||
}
|
}
|
||||||
|
|
||||||
get validateRelations(): validateRelations[] {
|
get validateRelations(): validateRelations[] {
|
||||||
return [];
|
const timeGroupId = this.data.time_group_id ?? this.data.time_group?.id;
|
||||||
|
const relation =
|
||||||
|
this.data.bundling_items?.length > 0
|
||||||
|
? 'bundling_items'
|
||||||
|
: 'bundling_parents';
|
||||||
|
return timeGroupId != null
|
||||||
|
? [
|
||||||
|
{
|
||||||
|
relation: relation,
|
||||||
|
singleQuery: ['time_group_id', '!=', timeGroupId],
|
||||||
|
message: `Gagal Update! Time group item dan bundling item tidak sama`,
|
||||||
|
},
|
||||||
|
]
|
||||||
|
: [];
|
||||||
}
|
}
|
||||||
|
|
||||||
get uniqueColumns(): columnUniques[] {
|
get uniqueColumns(): columnUniques[] {
|
||||||
return [{ column: 'name' }];
|
const timeGroupId = this.data.time_group_id ?? this.data.time_group?.id;
|
||||||
|
return timeGroupId != null
|
||||||
|
? [
|
||||||
|
{
|
||||||
|
column: 'name',
|
||||||
|
query: `(status = '${STATUS.ACTIVE}' AND (${this.tableName}.time_group_id Is Null OR ${this.tableName}.time_group_id = '${timeGroupId}'))`,
|
||||||
|
},
|
||||||
|
]
|
||||||
|
: [
|
||||||
|
{
|
||||||
|
column: 'name',
|
||||||
|
query: `(status = '${STATUS.ACTIVE}')`,
|
||||||
|
},
|
||||||
|
];
|
||||||
}
|
}
|
||||||
|
|
||||||
get eventTopics(): EventTopics[] {
|
get eventTopics(): EventTopics[] {
|
||||||
|
|
|
@ -53,9 +53,11 @@ export class DetailItemManager extends BaseDetailManager<ItemEntity> {
|
||||||
`${this.tableName}.total_price`,
|
`${this.tableName}.total_price`,
|
||||||
`${this.tableName}.base_price`,
|
`${this.tableName}.base_price`,
|
||||||
`${this.tableName}.use_queue`,
|
`${this.tableName}.use_queue`,
|
||||||
|
`${this.tableName}.usage_type`,
|
||||||
`${this.tableName}.show_to_booking`,
|
`${this.tableName}.show_to_booking`,
|
||||||
`${this.tableName}.breakdown_bundling`,
|
`${this.tableName}.breakdown_bundling`,
|
||||||
`${this.tableName}.play_estimation`,
|
`${this.tableName}.play_estimation`,
|
||||||
|
`${this.tableName}.booking_description`,
|
||||||
|
|
||||||
`item_category.id`,
|
`item_category.id`,
|
||||||
`item_category.name`,
|
`item_category.name`,
|
||||||
|
|
|
@ -53,6 +53,9 @@ export class IndexItemManager extends BaseIndexManager<ItemEntity> {
|
||||||
`${this.tableName}.share_profit`,
|
`${this.tableName}.share_profit`,
|
||||||
`${this.tableName}.breakdown_bundling`,
|
`${this.tableName}.breakdown_bundling`,
|
||||||
`${this.tableName}.play_estimation`,
|
`${this.tableName}.play_estimation`,
|
||||||
|
`${this.tableName}.show_to_booking`,
|
||||||
|
`${this.tableName}.booking_description`,
|
||||||
|
`${this.tableName}.usage_type`,
|
||||||
|
|
||||||
`item_category.id`,
|
`item_category.id`,
|
||||||
`item_category.name`,
|
`item_category.name`,
|
||||||
|
@ -106,10 +109,29 @@ export class IndexItemManager extends BaseIndexManager<ItemEntity> {
|
||||||
queryBuilder.andWhere(`${this.tableName}.tenant_id Is Null`);
|
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) {
|
if (this.filterParam.show_to_booking) {
|
||||||
queryBuilder.andWhere(`${this.tableName}.show_to_booking = true`);
|
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;
|
return queryBuilder;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -8,6 +8,7 @@ import {
|
||||||
columnUniques,
|
columnUniques,
|
||||||
validateRelations,
|
validateRelations,
|
||||||
} from 'src/core/strings/constants/interface.constants';
|
} from 'src/core/strings/constants/interface.constants';
|
||||||
|
import { STATUS } from 'src/core/strings/constants/base.constants';
|
||||||
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
export class UpdateItemManager extends BaseUpdateManager<ItemEntity> {
|
export class UpdateItemManager extends BaseUpdateManager<ItemEntity> {
|
||||||
|
@ -39,11 +40,31 @@ export class UpdateItemManager extends BaseUpdateManager<ItemEntity> {
|
||||||
}
|
}
|
||||||
|
|
||||||
get validateRelations(): validateRelations[] {
|
get validateRelations(): validateRelations[] {
|
||||||
return [];
|
const timeGroupId = this.data.time_group_id ?? this.data.time_group?.id;
|
||||||
|
const relation =
|
||||||
|
this.data.bundling_items?.length > 0
|
||||||
|
? 'bundling_items'
|
||||||
|
: 'bundling_parents';
|
||||||
|
|
||||||
|
return timeGroupId != null
|
||||||
|
? [
|
||||||
|
{
|
||||||
|
relation: relation,
|
||||||
|
singleQuery: ['time_group_id', '!=', timeGroupId],
|
||||||
|
message: `Gagal Update! Time group item dan bundling item tidak sama`,
|
||||||
|
},
|
||||||
|
]
|
||||||
|
: [];
|
||||||
}
|
}
|
||||||
|
|
||||||
get uniqueColumns(): columnUniques[] {
|
get uniqueColumns(): columnUniques[] {
|
||||||
return [];
|
const timeGroupId = this.data.time_group_id ?? this.data.time_group?.id;
|
||||||
|
return [
|
||||||
|
{
|
||||||
|
column: 'name',
|
||||||
|
query: `(status = '${STATUS.ACTIVE}' AND (${this.tableName}.time_group_id Is Null OR ${this.tableName}.time_group_id = '${timeGroupId}'))`,
|
||||||
|
},
|
||||||
|
];
|
||||||
}
|
}
|
||||||
|
|
||||||
get entityTarget(): any {
|
get entityTarget(): any {
|
||||||
|
|
|
@ -16,6 +16,12 @@ export class FilterItemDto extends BaseFilterDto implements FilterItemEntity {
|
||||||
})
|
})
|
||||||
season_period_ids: string[];
|
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 })
|
@ApiProperty({ type: ['string'], required: false })
|
||||||
@Transform((body) => {
|
@Transform((body) => {
|
||||||
return Array.isArray(body.value) ? body.value : [body.value];
|
return Array.isArray(body.value) ? body.value : [body.value];
|
||||||
|
|
|
@ -138,6 +138,17 @@ export class ItemDto extends BaseStatusDto implements ItemEntity {
|
||||||
@ValidateIf((body) => body.show_to_booking)
|
@ValidateIf((body) => body.show_to_booking)
|
||||||
show_to_booking: boolean;
|
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({
|
@ApiProperty({
|
||||||
name: 'bundling_items',
|
name: 'bundling_items',
|
||||||
type: [Object],
|
type: [Object],
|
||||||
|
|
|
@ -6,6 +6,7 @@ import {
|
||||||
Patch,
|
Patch,
|
||||||
Post,
|
Post,
|
||||||
Put,
|
Put,
|
||||||
|
UseGuards,
|
||||||
} from '@nestjs/common';
|
} from '@nestjs/common';
|
||||||
import { ItemDataOrchestrator } from '../domain/usecases/item-data.orchestrator';
|
import { ItemDataOrchestrator } from '../domain/usecases/item-data.orchestrator';
|
||||||
import { ItemDto } from './dto/item.dto';
|
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 { BatchIdsDto } from 'src/core/modules/infrastructure/dto/base-batch.dto';
|
||||||
import { Public } from 'src/core/guards';
|
import { Public } from 'src/core/guards';
|
||||||
import { UpdateItemPriceDto } from './dto/update-item-price.dto';
|
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`)
|
@ApiTags(`${MODULE_NAME.ITEM.split('-').join(' ')} - data`)
|
||||||
@Controller(`v1/${MODULE_NAME.ITEM}`)
|
@Controller(`v1/${MODULE_NAME.ITEM}`)
|
||||||
|
@ -29,6 +31,7 @@ export class ItemDataController {
|
||||||
return await this.orchestrator.create(data);
|
return await this.orchestrator.create(data);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Public(true)
|
||||||
@Post('update-price')
|
@Post('update-price')
|
||||||
async updatePrice(@Body() body: UpdateItemPriceDto): Promise<any> {
|
async updatePrice(@Body() body: UpdateItemPriceDto): Promise<any> {
|
||||||
return await this.orchestrator.updatePrice(body);
|
return await this.orchestrator.updatePrice(body);
|
||||||
|
@ -40,6 +43,7 @@ export class ItemDataController {
|
||||||
}
|
}
|
||||||
|
|
||||||
@Patch(':id/active')
|
@Patch(':id/active')
|
||||||
|
@UseGuards(OtpCheckerGuard)
|
||||||
async active(@Param('id') dataId: string): Promise<string> {
|
async active(@Param('id') dataId: string): Promise<string> {
|
||||||
return await this.orchestrator.active(dataId);
|
return await this.orchestrator.active(dataId);
|
||||||
}
|
}
|
||||||
|
@ -50,6 +54,7 @@ export class ItemDataController {
|
||||||
}
|
}
|
||||||
|
|
||||||
@Patch(':id/confirm')
|
@Patch(':id/confirm')
|
||||||
|
@UseGuards(OtpCheckerGuard)
|
||||||
async confirm(@Param('id') dataId: string): Promise<string> {
|
async confirm(@Param('id') dataId: string): Promise<string> {
|
||||||
return await this.orchestrator.confirm(dataId);
|
return await this.orchestrator.confirm(dataId);
|
||||||
}
|
}
|
||||||
|
@ -70,6 +75,7 @@ export class ItemDataController {
|
||||||
}
|
}
|
||||||
|
|
||||||
@Put(':id')
|
@Put(':id')
|
||||||
|
@UseGuards(OtpCheckerGuard)
|
||||||
async update(
|
async update(
|
||||||
@Param('id') dataId: string,
|
@Param('id') dataId: string,
|
||||||
@Body() data: ItemDto,
|
@Body() data: ItemDto,
|
||||||
|
|
|
@ -0,0 +1,80 @@
|
||||||
|
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';
|
||||||
|
import * as moment from 'moment';
|
||||||
|
import { ORDER_TYPE } from 'src/core/strings/constants/base.constants';
|
||||||
|
|
||||||
|
// TODO:
|
||||||
|
// Implementasikan filter by start_time, end_timen, dan max_usage_time
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class IndexPublicTimeGroupManager extends BaseIndexManager<TimeGroupEntity> {
|
||||||
|
async prepareData(): Promise<void> {
|
||||||
|
Object.assign(this.filterParam, {
|
||||||
|
order_by: `${this.tableName}.start_time`,
|
||||||
|
order_type: ORDER_TYPE.ASC,
|
||||||
|
});
|
||||||
|
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`);
|
||||||
|
|
||||||
|
if (!this.filterParam.date) {
|
||||||
|
const currentTime = moment().utcOffset('+07:00').format('HH:mm:ss');
|
||||||
|
|
||||||
|
queryBuilder.andWhere(`${this.tableName}.end_time >= :current_time`, {
|
||||||
|
current_time: currentTime,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
return queryBuilder;
|
||||||
|
}
|
||||||
|
}
|
|
@ -6,11 +6,13 @@ import { PaginationResponse } from 'src/core/response/domain/ok-response.interfa
|
||||||
import { BaseReadOrchestrator } from 'src/core/modules/domain/usecase/orchestrators/base-read.orchestrator';
|
import { BaseReadOrchestrator } from 'src/core/modules/domain/usecase/orchestrators/base-read.orchestrator';
|
||||||
import { DetailTimeGroupManager } from './managers/detail-time-group.manager';
|
import { DetailTimeGroupManager } from './managers/detail-time-group.manager';
|
||||||
import { TABLE_NAME } from 'src/core/strings/constants/table.constants';
|
import { TABLE_NAME } from 'src/core/strings/constants/table.constants';
|
||||||
|
import { IndexPublicTimeGroupManager } from './managers/index-public-time-group.manager';
|
||||||
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
export class TimeGroupReadOrchestrator extends BaseReadOrchestrator<TimeGroupEntity> {
|
export class TimeGroupReadOrchestrator extends BaseReadOrchestrator<TimeGroupEntity> {
|
||||||
constructor(
|
constructor(
|
||||||
private indexManager: IndexTimeGroupManager,
|
private indexManager: IndexTimeGroupManager,
|
||||||
|
private indexPublicManager: IndexPublicTimeGroupManager,
|
||||||
private detailManager: DetailTimeGroupManager,
|
private detailManager: DetailTimeGroupManager,
|
||||||
private serviceData: TimeGroupReadService,
|
private serviceData: TimeGroupReadService,
|
||||||
) {
|
) {
|
||||||
|
@ -24,6 +26,16 @@ export class TimeGroupReadOrchestrator extends BaseReadOrchestrator<TimeGroupEnt
|
||||||
return this.indexManager.getResult();
|
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> {
|
async detail(dataId: string): Promise<TimeGroupEntity> {
|
||||||
this.detailManager.setData(dataId);
|
this.detailManager.setData(dataId);
|
||||||
this.detailManager.setService(this.serviceData, TABLE_NAME.TIME_GROUPS);
|
this.detailManager.setService(this.serviceData, TABLE_NAME.TIME_GROUPS);
|
||||||
|
|
|
@ -30,4 +30,12 @@ export class FilterTimeGroupDto
|
||||||
@ApiProperty({ type: 'string', required: false })
|
@ApiProperty({ type: 'string', required: false })
|
||||||
@ValidateIf((body) => body.max_usage_time_to)
|
@ValidateIf((body) => body.max_usage_time_to)
|
||||||
max_usage_time_to: string;
|
max_usage_time_to: string;
|
||||||
|
|
||||||
|
@ApiProperty({
|
||||||
|
type: Date,
|
||||||
|
required: false,
|
||||||
|
example: '2024-01-01',
|
||||||
|
})
|
||||||
|
@ValidateIf((body) => body.date)
|
||||||
|
date: Date;
|
||||||
}
|
}
|
||||||
|
|
|
@ -28,3 +28,19 @@ export class TimeGroupReadController {
|
||||||
return await this.orchestrator.detail(id);
|
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);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
|
@ -4,7 +4,10 @@ import { TypeOrmModule } from '@nestjs/typeorm';
|
||||||
import { CONNECTION_NAME } from 'src/core/strings/constants/base.constants';
|
import { CONNECTION_NAME } from 'src/core/strings/constants/base.constants';
|
||||||
import { TimeGroupDataService } from './data/services/time-group-data.service';
|
import { TimeGroupDataService } from './data/services/time-group-data.service';
|
||||||
import { TimeGroupReadService } from './data/services/time-group-read.service';
|
import { TimeGroupReadService } from './data/services/time-group-read.service';
|
||||||
import { TimeGroupReadController } from './infrastructure/time-group-read.controller';
|
import {
|
||||||
|
TimeGroupPublicReadController,
|
||||||
|
TimeGroupReadController,
|
||||||
|
} from './infrastructure/time-group-read.controller';
|
||||||
import { TimeGroupReadOrchestrator } from './domain/usecases/time-group-read.orchestrator';
|
import { TimeGroupReadOrchestrator } from './domain/usecases/time-group-read.orchestrator';
|
||||||
import { TimeGroupDataController } from './infrastructure/time-group-data.controller';
|
import { TimeGroupDataController } from './infrastructure/time-group-data.controller';
|
||||||
import { TimeGroupDataOrchestrator } from './domain/usecases/time-group-data.orchestrator';
|
import { TimeGroupDataOrchestrator } from './domain/usecases/time-group-data.orchestrator';
|
||||||
|
@ -22,6 +25,7 @@ import { BatchActiveTimeGroupManager } from './domain/usecases/managers/batch-ac
|
||||||
import { BatchConfirmTimeGroupManager } from './domain/usecases/managers/batch-confirm-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 { BatchInactiveTimeGroupManager } from './domain/usecases/managers/batch-inactive-time-group.manager';
|
||||||
import { TimeGroupModel } from './data/models/time-group.model';
|
import { TimeGroupModel } from './data/models/time-group.model';
|
||||||
|
import { IndexPublicTimeGroupManager } from './domain/usecases/managers/index-public-time-group.manager';
|
||||||
|
|
||||||
@Module({
|
@Module({
|
||||||
imports: [
|
imports: [
|
||||||
|
@ -29,8 +33,13 @@ import { TimeGroupModel } from './data/models/time-group.model';
|
||||||
TypeOrmModule.forFeature([TimeGroupModel], CONNECTION_NAME.DEFAULT),
|
TypeOrmModule.forFeature([TimeGroupModel], CONNECTION_NAME.DEFAULT),
|
||||||
CqrsModule,
|
CqrsModule,
|
||||||
],
|
],
|
||||||
controllers: [TimeGroupDataController, TimeGroupReadController],
|
controllers: [
|
||||||
|
TimeGroupDataController,
|
||||||
|
TimeGroupReadController,
|
||||||
|
TimeGroupPublicReadController,
|
||||||
|
],
|
||||||
providers: [
|
providers: [
|
||||||
|
IndexPublicTimeGroupManager,
|
||||||
IndexTimeGroupManager,
|
IndexTimeGroupManager,
|
||||||
DetailTimeGroupManager,
|
DetailTimeGroupManager,
|
||||||
CreateTimeGroupManager,
|
CreateTimeGroupManager,
|
||||||
|
|
|
@ -40,35 +40,38 @@ export class TicketDataService extends BaseDataService<QueueTicket> {
|
||||||
}
|
}
|
||||||
|
|
||||||
async loginQueue(id: string): Promise<QueueOrder> {
|
async loginQueue(id: string): Promise<QueueOrder> {
|
||||||
|
const start = moment().startOf('day').valueOf();
|
||||||
|
const end = moment().endOf('day').valueOf();
|
||||||
|
|
||||||
const order = await this.order.findOne({
|
const order = await this.order.findOne({
|
||||||
relations: ['tickets'],
|
relations: ['tickets'],
|
||||||
where: [
|
where: [
|
||||||
{ transaction_id: id },
|
{ transaction_id: id, date: Between(start, end) },
|
||||||
{ code: id, transaction_id: Not(IsNull()) },
|
{ code: id, transaction_id: Not(IsNull()), date: Between(start, end) },
|
||||||
],
|
],
|
||||||
});
|
});
|
||||||
|
|
||||||
if (!order) {
|
// if (!order) {
|
||||||
const { customer_name, customer_phone } =
|
// const { customer_name, customer_phone } =
|
||||||
await this.transaction.findOneOrFail({
|
// await this.transaction.findOneOrFail({
|
||||||
where: {
|
// where: {
|
||||||
id,
|
// id,
|
||||||
},
|
// },
|
||||||
});
|
// });
|
||||||
|
|
||||||
const start = moment().startOf('day').valueOf();
|
// const start = moment().startOf('day').valueOf();
|
||||||
const end = moment().endOf('day').valueOf();
|
// const end = moment().endOf('day').valueOf();
|
||||||
const order = this.order.findOneOrFail({
|
// const order = this.order.findOneOrFail({
|
||||||
relations: ['tickets'],
|
// relations: ['tickets'],
|
||||||
where: {
|
// where: {
|
||||||
customer: customer_name,
|
// customer: customer_name,
|
||||||
phone: customer_phone,
|
// phone: customer_phone,
|
||||||
date: Between(start, end),
|
// date: Between(start, end),
|
||||||
},
|
// },
|
||||||
});
|
// });
|
||||||
|
|
||||||
return order;
|
// return order;
|
||||||
}
|
// }
|
||||||
|
|
||||||
return order;
|
return order;
|
||||||
}
|
}
|
||||||
|
|
|
@ -56,7 +56,7 @@ export class QueueOrchestrator {
|
||||||
return order;
|
return order;
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
throw new UnauthorizedException({
|
throw new UnauthorizedException({
|
||||||
message: 'Invoice tidak ditemukan',
|
message: 'Invoice tidak ditemukan untuk tanggal hari ini',
|
||||||
error: 'INVOICE_NOT_FOUND',
|
error: 'INVOICE_NOT_FOUND',
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
|
@ -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 { QueueTimeFormula } from './domain/usecases/formula/queue-time.formula';
|
||||||
import { QueueJobController } from './infrastructure/controllers/queue-job.controller';
|
import { QueueJobController } from './infrastructure/controllers/queue-job.controller';
|
||||||
import { GenerateQueueManager } from './domain/usecases/generate-queue.manager';
|
import { GenerateQueueManager } from './domain/usecases/generate-queue.manager';
|
||||||
|
import { CouchModule } from 'src/modules/configuration/couch/couch.module';
|
||||||
@Module({
|
@Module({
|
||||||
imports: [
|
imports: [
|
||||||
ConfigModule.forRoot(),
|
ConfigModule.forRoot(),
|
||||||
|
@ -57,6 +57,7 @@ import { GenerateQueueManager } from './domain/usecases/generate-queue.manager';
|
||||||
CONNECTION_NAME.DEFAULT,
|
CONNECTION_NAME.DEFAULT,
|
||||||
),
|
),
|
||||||
CqrsModule,
|
CqrsModule,
|
||||||
|
CouchModule,
|
||||||
],
|
],
|
||||||
controllers: [QueueController, QueueAdminController, QueueJobController],
|
controllers: [QueueController, QueueAdminController, QueueJobController],
|
||||||
providers: [
|
providers: [
|
||||||
|
|
|
@ -6,6 +6,7 @@ import {
|
||||||
Patch,
|
Patch,
|
||||||
Post,
|
Post,
|
||||||
Put,
|
Put,
|
||||||
|
UseGuards,
|
||||||
} from '@nestjs/common';
|
} from '@nestjs/common';
|
||||||
import { SeasonPeriodDataOrchestrator } from '../domain/usecases/season-period-data.orchestrator';
|
import { SeasonPeriodDataOrchestrator } from '../domain/usecases/season-period-data.orchestrator';
|
||||||
import { SeasonPeriodDto } from './dto/season-period.dto';
|
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 { UpdateSeasonPeriodDto } from './dto/update-season-period.dto';
|
||||||
import { UpdateSeasonPeriodItemDto } from './dto/update-season-period-item.dto';
|
import { UpdateSeasonPeriodItemDto } from './dto/update-season-period-item.dto';
|
||||||
import { UpdateSeasonPriceDto } from './dto/update-season-price.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`)
|
@ApiTags(`${MODULE_NAME.SEASON_PERIOD.split('-').join(' ')} - data`)
|
||||||
@Controller(`v1/${MODULE_NAME.SEASON_PERIOD}`)
|
@Controller(`v1/${MODULE_NAME.SEASON_PERIOD}`)
|
||||||
|
@ -27,11 +29,13 @@ export class SeasonPeriodDataController {
|
||||||
constructor(private orchestrator: SeasonPeriodDataOrchestrator) {}
|
constructor(private orchestrator: SeasonPeriodDataOrchestrator) {}
|
||||||
|
|
||||||
@Post()
|
@Post()
|
||||||
|
@UseGuards(OtpCheckerGuard)
|
||||||
async create(@Body() data: SeasonPeriodDto): Promise<SeasonPeriodEntity> {
|
async create(@Body() data: SeasonPeriodDto): Promise<SeasonPeriodEntity> {
|
||||||
return await this.orchestrator.create(data);
|
return await this.orchestrator.create(data);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Post('/update-price')
|
@Post('/update-price')
|
||||||
|
@UseGuards(OtpCheckerGuard)
|
||||||
async updatePrice(@Body() body: UpdateSeasonPriceDto): Promise<BatchResult> {
|
async updatePrice(@Body() body: UpdateSeasonPriceDto): Promise<BatchResult> {
|
||||||
return await this.orchestrator.updatePrice(body);
|
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
|
// pemisahan update data dengan update items dikarenakan payload (based on tampilan) berbeda
|
||||||
|
// TODO => simpan OTP update yang disikim dari request ini
|
||||||
@Put(':id/items')
|
@Put(':id/items')
|
||||||
|
@UseGuards(OtpCheckerGuard)
|
||||||
async updateItems(
|
async updateItems(
|
||||||
@Param('id') dataId: string,
|
@Param('id') dataId: string,
|
||||||
@Body() data: UpdateSeasonPeriodItemDto,
|
@Body() data: UpdateSeasonPeriodItemDto,
|
||||||
|
|
|
@ -15,6 +15,12 @@ import { TransactionEntity } from 'src/modules/transaction/transaction/domain/en
|
||||||
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
export class CancelReconciliationManager extends BaseUpdateStatusManager<TransactionEntity> {
|
export class CancelReconciliationManager extends BaseUpdateStatusManager<TransactionEntity> {
|
||||||
|
protected payloadBody: any;
|
||||||
|
|
||||||
|
setCustomBodyRequest(body) {
|
||||||
|
this.payloadBody = body;
|
||||||
|
}
|
||||||
|
|
||||||
getResult(): string {
|
getResult(): string {
|
||||||
return `Success active data ${this.result.id}`;
|
return `Success active data ${this.result.id}`;
|
||||||
}
|
}
|
||||||
|
@ -50,6 +56,7 @@ export class CancelReconciliationManager extends BaseUpdateStatusManager<Transac
|
||||||
async beforeProcess(): Promise<void> {
|
async beforeProcess(): Promise<void> {
|
||||||
if (this.data.is_recap_transaction) {
|
if (this.data.is_recap_transaction) {
|
||||||
Object.assign(this.data, {
|
Object.assign(this.data, {
|
||||||
|
otp_code: this.payloadBody?.otp_code,
|
||||||
reconciliation_confirm_by: null,
|
reconciliation_confirm_by: null,
|
||||||
reconciliation_confirm_date: null,
|
reconciliation_confirm_date: null,
|
||||||
reconciliation_status: STATUS.PENDING,
|
reconciliation_status: STATUS.PENDING,
|
||||||
|
@ -58,6 +65,7 @@ export class CancelReconciliationManager extends BaseUpdateStatusManager<Transac
|
||||||
});
|
});
|
||||||
} else {
|
} else {
|
||||||
Object.assign(this.data, {
|
Object.assign(this.data, {
|
||||||
|
otp_code: this.payloadBody?.otp_code,
|
||||||
reconciliation_mdr: this.data.reconciliation_mdr ?? null,
|
reconciliation_mdr: this.data.reconciliation_mdr ?? null,
|
||||||
reconciliation_confirm_by: this.user.name,
|
reconciliation_confirm_by: this.user.name,
|
||||||
reconciliation_confirm_date: new Date().getTime(),
|
reconciliation_confirm_date: new Date().getTime(),
|
||||||
|
@ -70,6 +78,7 @@ export class CancelReconciliationManager extends BaseUpdateStatusManager<Transac
|
||||||
: this.data.settlement_date,
|
: this.data.settlement_date,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
@ -58,9 +58,10 @@ export class ReconciliationDataOrchestrator {
|
||||||
return this.batchConfirmManager.getResult();
|
return this.batchConfirmManager.getResult();
|
||||||
}
|
}
|
||||||
|
|
||||||
async cancel(dataId): Promise<string> {
|
async cancel(dataId, body): Promise<string> {
|
||||||
this.cancelManager.setData(dataId, STATUS.REJECTED);
|
this.cancelManager.setData(dataId, STATUS.REJECTED);
|
||||||
this.cancelManager.setService(this.serviceData, TABLE_NAME.TRANSACTION);
|
this.cancelManager.setService(this.serviceData, TABLE_NAME.TRANSACTION);
|
||||||
|
this.cancelManager.setCustomBodyRequest(body);
|
||||||
await this.cancelManager.execute();
|
await this.cancelManager.execute();
|
||||||
return this.cancelManager.getResult();
|
return this.cancelManager.getResult();
|
||||||
}
|
}
|
||||||
|
|
|
@ -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;
|
||||||
|
}
|
|
@ -16,6 +16,7 @@ import { Public } from 'src/core/guards';
|
||||||
import { TransactionEntity } from '../../transaction/domain/entities/transaction.entity';
|
import { TransactionEntity } from '../../transaction/domain/entities/transaction.entity';
|
||||||
import { UpdateReconciliationDto } from './dto/reconciliation.dto';
|
import { UpdateReconciliationDto } from './dto/reconciliation.dto';
|
||||||
import { RecapReconciliationDto } from './dto/recap.dto';
|
import { RecapReconciliationDto } from './dto/recap.dto';
|
||||||
|
import { OtpVerifyDto } from './dto/cancel-top-dto';
|
||||||
|
|
||||||
@ApiTags(`${MODULE_NAME.RECONCILIATION.split('-').join(' ')} - data`)
|
@ApiTags(`${MODULE_NAME.RECONCILIATION.split('-').join(' ')} - data`)
|
||||||
@Controller(`v1/${MODULE_NAME.RECONCILIATION}`)
|
@Controller(`v1/${MODULE_NAME.RECONCILIATION}`)
|
||||||
|
@ -40,8 +41,11 @@ export class ReconciliationDataController {
|
||||||
}
|
}
|
||||||
|
|
||||||
@Patch(':id/cancel')
|
@Patch(':id/cancel')
|
||||||
async cancel(@Param('id') dataId: string): Promise<string> {
|
async cancel(
|
||||||
return await this.orchestrator.cancel(dataId);
|
@Param('id') dataId: string,
|
||||||
|
@Body() body: OtpVerifyDto,
|
||||||
|
): Promise<string> {
|
||||||
|
return await this.orchestrator.cancel(dataId, body);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Put('/batch-cancel')
|
@Put('/batch-cancel')
|
||||||
|
|
|
@ -19,13 +19,13 @@ import { BatchCancelReconciliationManager } from './domain/usecases/managers/bat
|
||||||
import { BatchConfirmReconciliationManager } from './domain/usecases/managers/batch-confirm-reconciliation.manager';
|
import { BatchConfirmReconciliationManager } from './domain/usecases/managers/batch-confirm-reconciliation.manager';
|
||||||
import { RecapReconciliationManager } from './domain/usecases/managers/recap-reconciliation.manager';
|
import { RecapReconciliationManager } from './domain/usecases/managers/recap-reconciliation.manager';
|
||||||
import { RecapPosTransactionHandler } from './domain/usecases/handlers/recap-pos-transaction.handler';
|
import { RecapPosTransactionHandler } from './domain/usecases/handlers/recap-pos-transaction.handler';
|
||||||
import { SalesPriceFormulaDataService } from '../sales-price-formula/data/services/sales-price-formula-data.service';
|
import { CouchModule } from 'src/modules/configuration/couch/couch.module';
|
||||||
|
|
||||||
@Module({
|
@Module({
|
||||||
imports: [
|
imports: [
|
||||||
ConfigModule.forRoot(),
|
ConfigModule.forRoot(),
|
||||||
TypeOrmModule.forFeature([TransactionModel], CONNECTION_NAME.DEFAULT),
|
TypeOrmModule.forFeature([TransactionModel], CONNECTION_NAME.DEFAULT),
|
||||||
CqrsModule,
|
CqrsModule,
|
||||||
|
CouchModule,
|
||||||
],
|
],
|
||||||
controllers: [ReconciliationDataController, ReconciliationReadController],
|
controllers: [ReconciliationDataController, ReconciliationReadController],
|
||||||
providers: [
|
providers: [
|
||||||
|
|
|
@ -31,6 +31,10 @@ export class DetailRefundManager extends BaseDetailManager<RefundEntity> {
|
||||||
'items.bundling_items',
|
'items.bundling_items',
|
||||||
'items.refunds item_refunds',
|
'items.refunds item_refunds',
|
||||||
'item_refunds.refund item_refunds_refund',
|
'item_refunds.refund item_refunds_refund',
|
||||||
|
|
||||||
|
'transaction.items transaction_items',
|
||||||
|
'transaction_items.item transaction_items_item',
|
||||||
|
'transaction_items_item.time_group transaction_items_item_time_group',
|
||||||
],
|
],
|
||||||
|
|
||||||
// relation yang hanya ingin dihitung (akan return number)
|
// relation yang hanya ingin dihitung (akan return number)
|
||||||
|
@ -65,6 +69,10 @@ export class DetailRefundManager extends BaseDetailManager<RefundEntity> {
|
||||||
'item_refunds',
|
'item_refunds',
|
||||||
'item_refunds_refund.id',
|
'item_refunds_refund.id',
|
||||||
'item_refunds_refund.status',
|
'item_refunds_refund.status',
|
||||||
|
|
||||||
|
'transaction_items',
|
||||||
|
'transaction_items_item',
|
||||||
|
'transaction_items_item_time_group',
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
@ -23,7 +23,7 @@ import { CancelRefundManager } from './domain/usecases/managers/cancel-refund.ma
|
||||||
import { RefundItemModel } from './data/models/refund-item.model';
|
import { RefundItemModel } from './data/models/refund-item.model';
|
||||||
import { TransactionDataService } from '../transaction/data/services/transaction-data.service';
|
import { TransactionDataService } from '../transaction/data/services/transaction-data.service';
|
||||||
import { TransactionModel } from '../transaction/data/models/transaction.model';
|
import { TransactionModel } from '../transaction/data/models/transaction.model';
|
||||||
|
import { CouchModule } from 'src/modules/configuration/couch/couch.module';
|
||||||
@Module({
|
@Module({
|
||||||
imports: [
|
imports: [
|
||||||
ConfigModule.forRoot(),
|
ConfigModule.forRoot(),
|
||||||
|
@ -32,6 +32,7 @@ import { TransactionModel } from '../transaction/data/models/transaction.model';
|
||||||
CONNECTION_NAME.DEFAULT,
|
CONNECTION_NAME.DEFAULT,
|
||||||
),
|
),
|
||||||
CqrsModule,
|
CqrsModule,
|
||||||
|
CouchModule,
|
||||||
],
|
],
|
||||||
controllers: [RefundDataController, RefundReadController],
|
controllers: [RefundDataController, RefundReadController],
|
||||||
providers: [
|
providers: [
|
||||||
|
|
|
@ -275,6 +275,22 @@ export class TransactionModel
|
||||||
})
|
})
|
||||||
refunds: RefundModel[];
|
refunds: RefundModel[];
|
||||||
|
|
||||||
|
@Column('varchar', { name: 'parent_id', nullable: true })
|
||||||
|
parent_id: string;
|
||||||
|
|
||||||
|
@ManyToOne(() => TransactionModel, (model) => model.id, {
|
||||||
|
nullable: true,
|
||||||
|
})
|
||||||
|
@JoinColumn({ name: 'parent_id' })
|
||||||
|
parent_transaction: TransactionModel;
|
||||||
|
|
||||||
|
@OneToMany(() => TransactionModel, (model) => model.parent_transaction, {
|
||||||
|
cascade: true,
|
||||||
|
onDelete: 'CASCADE',
|
||||||
|
onUpdate: 'CASCADE',
|
||||||
|
})
|
||||||
|
children_transactions: TransactionModel[];
|
||||||
|
|
||||||
@Column('varchar', { name: 'otp_code', nullable: true })
|
@Column('varchar', { name: 'otp_code', nullable: true })
|
||||||
otp_code: string;
|
otp_code: string;
|
||||||
}
|
}
|
||||||
|
|
|
@ -4,13 +4,32 @@ import { InjectRepository } from '@nestjs/typeorm';
|
||||||
import { TransactionModel } from '../models/transaction.model';
|
import { TransactionModel } from '../models/transaction.model';
|
||||||
import { CONNECTION_NAME } from 'src/core/strings/constants/base.constants';
|
import { CONNECTION_NAME } from 'src/core/strings/constants/base.constants';
|
||||||
import { Repository } from 'typeorm';
|
import { Repository } from 'typeorm';
|
||||||
|
import { CouchService } from 'src/modules/configuration/couch/data/services/couch.service';
|
||||||
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
export class TransactionDataService extends BaseDataService<TransactionModel> {
|
export class TransactionDataService extends BaseDataService<TransactionModel> {
|
||||||
constructor(
|
constructor(
|
||||||
@InjectRepository(TransactionModel, CONNECTION_NAME.DEFAULT)
|
@InjectRepository(TransactionModel, CONNECTION_NAME.DEFAULT)
|
||||||
private repo: Repository<TransactionModel>,
|
private repo: Repository<TransactionModel>,
|
||||||
|
private couchService: CouchService,
|
||||||
) {
|
) {
|
||||||
super(repo);
|
super(repo);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async getTransactionWithReschedule(booking_id: string) {
|
||||||
|
return this.repo.findOne({
|
||||||
|
relations: ['children_transactions', 'items'],
|
||||||
|
where: { id: booking_id },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async saveTransactionToCouch(transaction) {
|
||||||
|
const id = transaction.id ?? transaction._id;
|
||||||
|
const couchData = await this.couchService.getDoc(id, 'transaction');
|
||||||
|
if (!couchData) {
|
||||||
|
await this.couchService.createDoc(transaction, 'transaction');
|
||||||
|
} else {
|
||||||
|
await this.couchService.updateDoc(transaction, 'transaction');
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -30,4 +30,64 @@ export class TransactionReadService extends BaseReadService<TransactionEntity> {
|
||||||
|
|
||||||
return transactions;
|
return transactions;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async getSummary(posId: string, startDate: string) {
|
||||||
|
const query = `select payment_type_counter, payment_type_method_name, sum(payment_total) payment_total, sum(payment_total_pay) payment_total_pay
|
||||||
|
from transactions t
|
||||||
|
where 1=1
|
||||||
|
and t.creator_counter_no IN (${posId})
|
||||||
|
and invoice_date = '${startDate}'
|
||||||
|
and status = 'settled'
|
||||||
|
group by payment_type_counter, payment_type_method_name;`;
|
||||||
|
const transactions = await this.repo.query(query);
|
||||||
|
|
||||||
|
const qtyQuery = `select ti.item_id, ti.item_name, sum(ti.qty) total_qty, count(ti.item_name), sum(ti.qty), string_agg(distinct ti.item_price::text, '') price,
|
||||||
|
sum(payment_total) payment_total, sum(payment_total_pay) payment_total_pay
|
||||||
|
from transactions t
|
||||||
|
inner join transaction_items ti on t.id = ti.transaction_id
|
||||||
|
where t.creator_counter_no IN (${posId})
|
||||||
|
and invoice_date = '${startDate}'
|
||||||
|
and t.status = 'settled'
|
||||||
|
group by ti.item_name, ti.item_id`;
|
||||||
|
const qtyTransactions = await this.repo.query(qtyQuery);
|
||||||
|
|
||||||
|
const totalSalesQuery = `select sum(payment_total) payment_total
|
||||||
|
from transactions t
|
||||||
|
where 1=1
|
||||||
|
and t.creator_counter_no IN (${posId})
|
||||||
|
and invoice_date = '${startDate}'
|
||||||
|
and status = 'settled'`;
|
||||||
|
const totalSales = await this.repo.query(totalSalesQuery);
|
||||||
|
|
||||||
|
return {
|
||||||
|
payment: transactions,
|
||||||
|
qty: qtyTransactions,
|
||||||
|
totalSales: totalSales?.[0]?.payment_total ?? 0,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
async getLastTransactionByPos(
|
||||||
|
posId: string,
|
||||||
|
): Promise<TransactionEntity | null> {
|
||||||
|
const transaction = await this.repo.findOne({
|
||||||
|
select: [
|
||||||
|
'id',
|
||||||
|
'created_at',
|
||||||
|
'updated_at',
|
||||||
|
'status',
|
||||||
|
'invoice_code',
|
||||||
|
'creator_counter_no',
|
||||||
|
'invoice_date',
|
||||||
|
'payment_total',
|
||||||
|
],
|
||||||
|
where: {
|
||||||
|
creator_counter_no: parseInt(posId),
|
||||||
|
},
|
||||||
|
order: {
|
||||||
|
created_at: 'DESC',
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
return transaction;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -86,6 +86,8 @@ export interface TransactionEntity extends BaseStatusEntity {
|
||||||
sending_qr_at: number;
|
sending_qr_at: number;
|
||||||
sending_qr_status: STATUS;
|
sending_qr_status: STATUS;
|
||||||
|
|
||||||
|
parent_id?: string;
|
||||||
|
|
||||||
calendar_id?: string;
|
calendar_id?: string;
|
||||||
calendar_link?: string;
|
calendar_link?: string;
|
||||||
|
|
||||||
|
|
|
@ -11,6 +11,9 @@ import { TransactionChangeStatusEvent } from '../../entities/event/transaction-c
|
||||||
import * as _ from 'lodash';
|
import * as _ from 'lodash';
|
||||||
import { TABLE_NAME } from 'src/core/strings/constants/table.constants';
|
import { TABLE_NAME } from 'src/core/strings/constants/table.constants';
|
||||||
import { generateInvoiceCodeHelper } from '../managers/helpers/generate-invoice-code.helper';
|
import { generateInvoiceCodeHelper } from '../managers/helpers/generate-invoice-code.helper';
|
||||||
|
import { TransactionType } from '../../../constants';
|
||||||
|
import { WhatsappService } from 'src/services/whatsapp/whatsapp.service';
|
||||||
|
import * as moment from 'moment';
|
||||||
|
|
||||||
@EventsHandler(MidtransCallbackEvent)
|
@EventsHandler(MidtransCallbackEvent)
|
||||||
export class MidtransCallbackHandler
|
export class MidtransCallbackHandler
|
||||||
|
@ -22,7 +25,6 @@ export class MidtransCallbackHandler
|
||||||
) {}
|
) {}
|
||||||
|
|
||||||
async handle(event: MidtransCallbackEvent) {
|
async handle(event: MidtransCallbackEvent) {
|
||||||
console.log('callbak mid', event);
|
|
||||||
const data_id = event.data.id;
|
const data_id = event.data.id;
|
||||||
const data = event.data.data;
|
const data = event.data.data;
|
||||||
let old_data = undefined;
|
let old_data = undefined;
|
||||||
|
@ -58,16 +60,38 @@ export class MidtransCallbackHandler
|
||||||
.manager.connection.createQueryRunner();
|
.manager.connection.createQueryRunner();
|
||||||
|
|
||||||
await this.dataService.create(queryRunner, TransactionModel, transaction);
|
await this.dataService.create(queryRunner, TransactionModel, transaction);
|
||||||
console.log('update change status to tr', {
|
|
||||||
id: data_id,
|
if (
|
||||||
old: old_data,
|
transaction.status === STATUS.SETTLED &&
|
||||||
data: { ...data, status: transaction.status },
|
transaction.type === TransactionType.ONLINE
|
||||||
user: BLANK_USER,
|
) {
|
||||||
description: 'Midtrans Callback',
|
const whatsappService = new WhatsappService();
|
||||||
module: TABLE_NAME.TRANSACTION,
|
const formattedDate = moment(transaction.booking_date);
|
||||||
op: OPERATION.UPDATE,
|
const payload = {
|
||||||
});
|
id: transaction.id,
|
||||||
console.log({ data, old_data });
|
phone: transaction.customer_phone,
|
||||||
|
code: transaction.invoice_code,
|
||||||
|
name: transaction.customer_name,
|
||||||
|
time: formattedDate.valueOf(),
|
||||||
|
};
|
||||||
|
await whatsappService.bookingCreated(payload);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (
|
||||||
|
transaction.status === STATUS.EXPIRED &&
|
||||||
|
transaction.type === TransactionType.ONLINE
|
||||||
|
) {
|
||||||
|
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.bookingExpired(payload);
|
||||||
|
}
|
||||||
|
|
||||||
this.eventBus.publish(
|
this.eventBus.publish(
|
||||||
new TransactionChangeStatusEvent({
|
new TransactionChangeStatusEvent({
|
||||||
|
|
|
@ -31,6 +31,9 @@ export class DetailTransactionManager extends BaseDetailManager<TransactionEntit
|
||||||
'items.refunds item_refunds',
|
'items.refunds item_refunds',
|
||||||
'item_refunds.refund item_refunds_refund',
|
'item_refunds.refund item_refunds_refund',
|
||||||
'refunds',
|
'refunds',
|
||||||
|
|
||||||
|
'items.item items_item',
|
||||||
|
'items_item.time_group items_item_time_group',
|
||||||
],
|
],
|
||||||
|
|
||||||
// relation yang hanya ingin dihitung (akan return number)
|
// relation yang hanya ingin dihitung (akan return number)
|
||||||
|
@ -92,6 +95,8 @@ export class DetailTransactionManager extends BaseDetailManager<TransactionEntit
|
||||||
'item_refunds_refund.status',
|
'item_refunds_refund.status',
|
||||||
|
|
||||||
'refunds',
|
'refunds',
|
||||||
|
'items_item',
|
||||||
|
'items_item_time_group',
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
@ -43,6 +43,8 @@ export function mappingTransaction(data, refundId?: string) {
|
||||||
if (refundId)
|
if (refundId)
|
||||||
refund = itemData.refunds?.find((item) => item.refund.id == refundId);
|
refund = itemData.refunds?.find((item) => item.refund.id == refundId);
|
||||||
|
|
||||||
|
const timeGroup = itemData?.item?.time_group;
|
||||||
|
|
||||||
return {
|
return {
|
||||||
item: {
|
item: {
|
||||||
id: itemData.item_id,
|
id: itemData.item_id,
|
||||||
|
@ -57,6 +59,7 @@ export function mappingTransaction(data, refundId?: string) {
|
||||||
},
|
},
|
||||||
breakdown_bundling: itemData.breakdown_bundling,
|
breakdown_bundling: itemData.breakdown_bundling,
|
||||||
bundling_items: itemData.bundling_items,
|
bundling_items: itemData.bundling_items,
|
||||||
|
time_group: timeGroup,
|
||||||
},
|
},
|
||||||
id: itemData.id,
|
id: itemData.id,
|
||||||
refund: refund,
|
refund: refund,
|
||||||
|
|
|
@ -141,4 +141,10 @@ export class TransactionDataOrchestrator {
|
||||||
await this.batchConfirmDataManager.execute();
|
await this.batchConfirmDataManager.execute();
|
||||||
return this.batchConfirmDataManager.getResult();
|
return this.batchConfirmDataManager.getResult();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async saveTransactionToCouch(transaction: any[]) {
|
||||||
|
for (const t of transaction) {
|
||||||
|
await this.serviceData.saveTransactionToCouch(t);
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -7,6 +7,8 @@ import { BaseReadOrchestrator } from 'src/core/modules/domain/usecase/orchestrat
|
||||||
import { DetailTransactionManager } from './managers/detail-transaction.manager';
|
import { DetailTransactionManager } from './managers/detail-transaction.manager';
|
||||||
import { TABLE_NAME } from 'src/core/strings/constants/table.constants';
|
import { TABLE_NAME } from 'src/core/strings/constants/table.constants';
|
||||||
import { PriceCalculator } from './calculator/price.calculator';
|
import { PriceCalculator } from './calculator/price.calculator';
|
||||||
|
import { In } from 'typeorm';
|
||||||
|
import * as moment from 'moment';
|
||||||
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
export class TransactionReadOrchestrator extends BaseReadOrchestrator<TransactionEntity> {
|
export class TransactionReadOrchestrator extends BaseReadOrchestrator<TransactionEntity> {
|
||||||
|
@ -26,6 +28,16 @@ export class TransactionReadOrchestrator extends BaseReadOrchestrator<Transactio
|
||||||
return this.indexManager.getResult();
|
return this.indexManager.getResult();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async summary(posId: string) {
|
||||||
|
const today = moment().format('YYYY-MM-DD');
|
||||||
|
const summary = await this.serviceData.getSummary(posId, today);
|
||||||
|
const lastTransaction = await this.serviceData.getLastTransactionByPos(
|
||||||
|
posId,
|
||||||
|
);
|
||||||
|
|
||||||
|
return { summary, lastTransaction };
|
||||||
|
}
|
||||||
|
|
||||||
async detail(dataId: string): Promise<TransactionEntity> {
|
async detail(dataId: string): Promise<TransactionEntity> {
|
||||||
this.detailManager.setData(dataId);
|
this.detailManager.setData(dataId);
|
||||||
this.detailManager.setService(this.serviceData, TABLE_NAME.TRANSACTION);
|
this.detailManager.setService(this.serviceData, TABLE_NAME.TRANSACTION);
|
||||||
|
@ -50,17 +62,24 @@ export class TransactionReadOrchestrator extends BaseReadOrchestrator<Transactio
|
||||||
transaction.payment_total_dpp = price.dpp_value;
|
transaction.payment_total_dpp = price.dpp_value;
|
||||||
transaction.payment_total_share = price.other.total_profit_share;
|
transaction.payment_total_share = price.other.total_profit_share;
|
||||||
transaction.payment_total_tax = price.other.payment_total_tax;
|
transaction.payment_total_tax = price.other.payment_total_tax;
|
||||||
console.log({ price }, transaction.payment_total);
|
console.log(transaction.id);
|
||||||
|
await this.serviceData.getRepository().save(transaction);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
ids = [];
|
||||||
|
|
||||||
async calculatePrice(): Promise<void> {
|
async calculatePrice(): Promise<void> {
|
||||||
const transactions = await this.serviceData.getManyByOptions({
|
const transactions = await this.serviceData.getManyByOptions({
|
||||||
where: {
|
where: {
|
||||||
is_recap_transaction: false,
|
// is_recap_transaction: false,
|
||||||
|
id: In(this.ids),
|
||||||
},
|
},
|
||||||
relations: ['items', 'items.bundling_items'],
|
relations: ['items', 'items.bundling_items'],
|
||||||
});
|
});
|
||||||
|
|
||||||
|
console.log(transactions.length);
|
||||||
|
// return;
|
||||||
|
|
||||||
for (const transaction of transactions) {
|
for (const transaction of transactions) {
|
||||||
try {
|
try {
|
||||||
const price = await this.calculator.calculate(transaction);
|
const price = await this.calculator.calculate(transaction);
|
||||||
|
|
|
@ -1,4 +1,5 @@
|
||||||
import {
|
import {
|
||||||
|
BadRequestException,
|
||||||
Body,
|
Body,
|
||||||
Controller,
|
Controller,
|
||||||
Delete,
|
Delete,
|
||||||
|
@ -7,17 +8,20 @@ import {
|
||||||
Post,
|
Post,
|
||||||
Put,
|
Put,
|
||||||
Res,
|
Res,
|
||||||
|
UseGuards,
|
||||||
} from '@nestjs/common';
|
} from '@nestjs/common';
|
||||||
import { Response } from 'express';
|
import { Response } from 'express';
|
||||||
import { TransactionDataOrchestrator } from '../domain/usecases/transaction-data.orchestrator';
|
import { TransactionDataOrchestrator } from '../domain/usecases/transaction-data.orchestrator';
|
||||||
import { TransactionDto } from './dto/transaction.dto';
|
import { TransactionDto } from './dto/transaction.dto';
|
||||||
import { MODULE_NAME } from 'src/core/strings/constants/module.constants';
|
import { MODULE_NAME } from 'src/core/strings/constants/module.constants';
|
||||||
import { ApiBearerAuth, ApiTags } from '@nestjs/swagger';
|
import { ApiBearerAuth, ApiBody, ApiTags } from '@nestjs/swagger';
|
||||||
import { TransactionEntity } from '../domain/entities/transaction.entity';
|
import { TransactionEntity } from '../domain/entities/transaction.entity';
|
||||||
import { BatchResult } from 'src/core/response/domain/ok-response.interface';
|
import { BatchResult } from 'src/core/response/domain/ok-response.interface';
|
||||||
import { BatchIdsDto } from 'src/core/modules/infrastructure/dto/base-batch.dto';
|
import { BatchIdsDto } from 'src/core/modules/infrastructure/dto/base-batch.dto';
|
||||||
import { Public } from 'src/core/guards';
|
import { Public } from 'src/core/guards';
|
||||||
import { DownloadPdfDto } from './dto/donwload-pdf.dto';
|
import { DownloadPdfDto } from './dto/donwload-pdf.dto';
|
||||||
|
import { OtpAuthGuard } from 'src/modules/configuration/otp-verification/infrastructure/guards/otp-auth.guard';
|
||||||
|
import { OtpCheckerGuard } from 'src/core/guards/domain/otp-checker.guard';
|
||||||
|
|
||||||
@ApiTags(`${MODULE_NAME.TRANSACTION.split('-').join(' ')} - data`)
|
@ApiTags(`${MODULE_NAME.TRANSACTION.split('-').join(' ')} - data`)
|
||||||
@Controller(`v1/${MODULE_NAME.TRANSACTION}`)
|
@Controller(`v1/${MODULE_NAME.TRANSACTION}`)
|
||||||
|
@ -50,6 +54,7 @@ export class TransactionDataController {
|
||||||
}
|
}
|
||||||
|
|
||||||
@Patch(':id/confirm-data')
|
@Patch(':id/confirm-data')
|
||||||
|
@UseGuards(OtpCheckerGuard)
|
||||||
async confirmData(@Param('id') dataId: string): Promise<string> {
|
async confirmData(@Param('id') dataId: string): Promise<string> {
|
||||||
return await this.orchestrator.confirmData(dataId);
|
return await this.orchestrator.confirmData(dataId);
|
||||||
}
|
}
|
||||||
|
@ -60,6 +65,7 @@ export class TransactionDataController {
|
||||||
}
|
}
|
||||||
|
|
||||||
@Patch(':id/confirm')
|
@Patch(':id/confirm')
|
||||||
|
@UseGuards(OtpCheckerGuard)
|
||||||
async confirm(@Param('id') dataId: string): Promise<string> {
|
async confirm(@Param('id') dataId: string): Promise<string> {
|
||||||
return await this.orchestrator.confirm(dataId);
|
return await this.orchestrator.confirm(dataId);
|
||||||
}
|
}
|
||||||
|
@ -91,4 +97,29 @@ export class TransactionDataController {
|
||||||
async delete(@Param('id') dataId: string): Promise<string> {
|
async delete(@Param('id') dataId: string): Promise<string> {
|
||||||
return await this.orchestrator.delete(dataId);
|
return await this.orchestrator.delete(dataId);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Post('save-to-couch')
|
||||||
|
@ApiBody({
|
||||||
|
schema: {
|
||||||
|
type: 'array',
|
||||||
|
items: {
|
||||||
|
type: 'object',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
})
|
||||||
|
@Public(true)
|
||||||
|
// @UseGuards(OtpAuthGuard)
|
||||||
|
async saveToCouch(@Body() body: any[]) {
|
||||||
|
try {
|
||||||
|
await this.orchestrator.saveTransactionToCouch(body);
|
||||||
|
return {
|
||||||
|
message: 'Success',
|
||||||
|
};
|
||||||
|
} catch (error) {
|
||||||
|
throw new BadRequestException({
|
||||||
|
message: error.message,
|
||||||
|
error: error.stack,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -28,6 +28,12 @@ export class TransactionReadController {
|
||||||
return await this.orchestrator.detail(id);
|
return await this.orchestrator.detail(id);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Public(true)
|
||||||
|
@Get('summary/:posId')
|
||||||
|
async summary(@Param('posId') posId: string) {
|
||||||
|
return await this.orchestrator.summary(posId);
|
||||||
|
}
|
||||||
|
|
||||||
@Public(true)
|
@Public(true)
|
||||||
@Get('dummy/:id')
|
@Get('dummy/:id')
|
||||||
async calculate(@Param('id') id: string): Promise<string> {
|
async calculate(@Param('id') id: string): Promise<string> {
|
||||||
|
|
|
@ -47,6 +47,9 @@ import { TransactionDemographyModel } from './data/models/transaction-demography
|
||||||
import { PriceCalculator } from './domain/usecases/calculator/price.calculator';
|
import { PriceCalculator } from './domain/usecases/calculator/price.calculator';
|
||||||
import { ItemModel } from 'src/modules/item-related/item/data/models/item.model';
|
import { ItemModel } from 'src/modules/item-related/item/data/models/item.model';
|
||||||
import { CouchModule } from 'src/modules/configuration/couch/couch.module';
|
import { CouchModule } from 'src/modules/configuration/couch/couch.module';
|
||||||
|
import { JWT_EXPIRED } from 'src/core/sessions/constants';
|
||||||
|
import { JWT_SECRET } from 'src/core/sessions/constants';
|
||||||
|
import { JwtModule } from '@nestjs/jwt';
|
||||||
|
|
||||||
@Module({
|
@Module({
|
||||||
exports: [
|
exports: [
|
||||||
|
@ -56,6 +59,10 @@ import { CouchModule } from 'src/modules/configuration/couch/couch.module';
|
||||||
],
|
],
|
||||||
imports: [
|
imports: [
|
||||||
ConfigModule.forRoot(),
|
ConfigModule.forRoot(),
|
||||||
|
JwtModule.register({
|
||||||
|
secret: JWT_SECRET,
|
||||||
|
signOptions: { expiresIn: JWT_EXPIRED },
|
||||||
|
}),
|
||||||
TypeOrmModule.forFeature(
|
TypeOrmModule.forFeature(
|
||||||
[
|
[
|
||||||
TransactionModel,
|
TransactionModel,
|
||||||
|
|
|
@ -6,6 +6,7 @@ import {
|
||||||
Patch,
|
Patch,
|
||||||
Post,
|
Post,
|
||||||
Put,
|
Put,
|
||||||
|
UseGuards,
|
||||||
} from '@nestjs/common';
|
} from '@nestjs/common';
|
||||||
import { UserDataOrchestrator } from '../domain/usecases/user-data.orchestrator';
|
import { UserDataOrchestrator } from '../domain/usecases/user-data.orchestrator';
|
||||||
import { UserDto } from './dto/user.dto';
|
import { UserDto } from './dto/user.dto';
|
||||||
|
@ -17,6 +18,7 @@ import { BatchIdsDto } from 'src/core/modules/infrastructure/dto/base-batch.dto'
|
||||||
import { Public } from 'src/core/guards';
|
import { Public } from 'src/core/guards';
|
||||||
import { UpdateUserDto } from './dto/update-user.dto';
|
import { UpdateUserDto } from './dto/update-user.dto';
|
||||||
import { UpdatePasswordUserDto } from './dto/update-password-user.dto';
|
import { UpdatePasswordUserDto } from './dto/update-password-user.dto';
|
||||||
|
import { OtpCheckerGuard } from 'src/core/guards/domain/otp-checker.guard';
|
||||||
|
|
||||||
@ApiTags(`${MODULE_NAME.USER.split('-').join(' ')} - data`)
|
@ApiTags(`${MODULE_NAME.USER.split('-').join(' ')} - data`)
|
||||||
@Controller(`v1/${MODULE_NAME.USER}`)
|
@Controller(`v1/${MODULE_NAME.USER}`)
|
||||||
|
@ -36,6 +38,7 @@ export class UserDataController {
|
||||||
}
|
}
|
||||||
|
|
||||||
@Patch(':id/active')
|
@Patch(':id/active')
|
||||||
|
@UseGuards(OtpCheckerGuard)
|
||||||
async active(@Param('id') dataId: string): Promise<string> {
|
async active(@Param('id') dataId: string): Promise<string> {
|
||||||
return await this.orchestrator.active(dataId);
|
return await this.orchestrator.active(dataId);
|
||||||
}
|
}
|
||||||
|
@ -46,6 +49,7 @@ export class UserDataController {
|
||||||
}
|
}
|
||||||
|
|
||||||
@Patch(':id/confirm')
|
@Patch(':id/confirm')
|
||||||
|
@UseGuards(OtpCheckerGuard)
|
||||||
async confirm(@Param('id') dataId: string): Promise<string> {
|
async confirm(@Param('id') dataId: string): Promise<string> {
|
||||||
return await this.orchestrator.confirm(dataId);
|
return await this.orchestrator.confirm(dataId);
|
||||||
}
|
}
|
||||||
|
|
|
@ -0,0 +1,7 @@
|
||||||
|
export interface WhatsappBookingCreate {
|
||||||
|
id: string;
|
||||||
|
phone: string;
|
||||||
|
code: string;
|
||||||
|
name: string;
|
||||||
|
time: number;
|
||||||
|
}
|
|
@ -1,6 +1,14 @@
|
||||||
export const WHATSAPP_BUSINESS_API_URL =
|
export const WHATSAPP_BUSINESS_API_URL =
|
||||||
process.env.WHATSAPP_BUSINESS_API_URL ?? 'https://graph.facebook.com/';
|
process.env.WHATSAPP_BUSINESS_API_URL ?? 'https://graph.facebook.com/';
|
||||||
|
|
||||||
|
export const BOOKING_QR_URL =
|
||||||
|
process.env.BOOKING_QR_URL ??
|
||||||
|
'https://www.drupal.org/files/project-images/qrcode-module_0.png?';
|
||||||
|
|
||||||
|
export const BOOKING_TICKET_URL =
|
||||||
|
process.env.BOOKING_TICKET_URL ??
|
||||||
|
'https://booking.sky.eigen.co.id/public/ticket/';
|
||||||
|
|
||||||
export const WHATSAPP_BUSINESS_VERSION =
|
export const WHATSAPP_BUSINESS_VERSION =
|
||||||
process.env.WHATSAPP_BUSINESS_VERSION ?? 'v22.0';
|
process.env.WHATSAPP_BUSINESS_VERSION ?? 'v22.0';
|
||||||
|
|
||||||
|
|
|
@ -4,6 +4,8 @@ import {
|
||||||
} from 'src/modules/queue/domain/helpers/time.helper';
|
} from 'src/modules/queue/domain/helpers/time.helper';
|
||||||
import { WhatsappQueue } from './entity/whatsapp-queue.entity';
|
import { WhatsappQueue } from './entity/whatsapp-queue.entity';
|
||||||
import {
|
import {
|
||||||
|
BOOKING_QR_URL,
|
||||||
|
BOOKING_TICKET_URL,
|
||||||
WHATSAPP_BUSINESS_ACCESS_TOKEN,
|
WHATSAPP_BUSINESS_ACCESS_TOKEN,
|
||||||
WHATSAPP_BUSINESS_ACCOUNT_NUMBER_ID,
|
WHATSAPP_BUSINESS_ACCOUNT_NUMBER_ID,
|
||||||
WHATSAPP_BUSINESS_API_URL,
|
WHATSAPP_BUSINESS_API_URL,
|
||||||
|
@ -13,6 +15,8 @@ import {
|
||||||
import axios from 'axios';
|
import axios from 'axios';
|
||||||
import { Logger } from '@nestjs/common';
|
import { Logger } from '@nestjs/common';
|
||||||
import { apm } from 'src/core/apm';
|
import { apm } from 'src/core/apm';
|
||||||
|
import { WhatsappBookingCreate } from './entity/booking.entity';
|
||||||
|
import * as moment from 'moment';
|
||||||
|
|
||||||
export class WhatsappService {
|
export class WhatsappService {
|
||||||
async sendMessage(data) {
|
async sendMessage(data) {
|
||||||
|
@ -36,6 +40,7 @@ export class WhatsappService {
|
||||||
status: error.response.status,
|
status: error.response.status,
|
||||||
data: error.response.data,
|
data: error.response.data,
|
||||||
headers: error.response.headers,
|
headers: error.response.headers,
|
||||||
|
error: error.response.data?.error?.error_data,
|
||||||
});
|
});
|
||||||
} else if (error.request) {
|
} else if (error.request) {
|
||||||
console.error('Axios error request:', error.request);
|
console.error('Axios error request:', error.request);
|
||||||
|
@ -118,6 +123,342 @@ export class WhatsappService {
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async bookingCreated(data: WhatsappBookingCreate) {
|
||||||
|
const imageUrl = `${BOOKING_QR_URL}${data.id}`;
|
||||||
|
|
||||||
|
const momentDate = moment(data.time);
|
||||||
|
const fallbackValue = momentDate.locale('id').format('dddd, DD MMMM YYYY');
|
||||||
|
// const dayOfWeek = momentDate.day();
|
||||||
|
// const dayOfMonth = momentDate.date();
|
||||||
|
// const year = momentDate.year();
|
||||||
|
// const month = momentDate.month() + 1;
|
||||||
|
// const hour = momentDate.hour();
|
||||||
|
// const minute = momentDate.minute();
|
||||||
|
|
||||||
|
const payload = {
|
||||||
|
messaging_product: 'whatsapp',
|
||||||
|
to: phoneNumberOnly(data.phone), // recipient's phone number
|
||||||
|
type: 'template',
|
||||||
|
template: {
|
||||||
|
name: 'booking_online',
|
||||||
|
language: {
|
||||||
|
code: 'id', // language code
|
||||||
|
},
|
||||||
|
components: [
|
||||||
|
{
|
||||||
|
type: 'header',
|
||||||
|
parameters: [
|
||||||
|
{
|
||||||
|
type: 'image',
|
||||||
|
image: {
|
||||||
|
link: imageUrl,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
type: 'body',
|
||||||
|
parameters: [
|
||||||
|
{
|
||||||
|
type: 'text',
|
||||||
|
parameter_name: 'customer',
|
||||||
|
text: data.name, // replace with name variable
|
||||||
|
},
|
||||||
|
{
|
||||||
|
type: 'text',
|
||||||
|
parameter_name: 'booking_code',
|
||||||
|
text: data.code, // replace with queue_code variable
|
||||||
|
},
|
||||||
|
{
|
||||||
|
type: 'text',
|
||||||
|
parameter_name: 'booking_date',
|
||||||
|
text: fallbackValue,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
type: 'button',
|
||||||
|
sub_type: 'url',
|
||||||
|
index: '0',
|
||||||
|
parameters: [
|
||||||
|
{
|
||||||
|
type: 'text',
|
||||||
|
text: data.id, // replace with dynamic URL
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
const response = await this.sendMessage(payload);
|
||||||
|
if (response)
|
||||||
|
Logger.log(
|
||||||
|
`Notification register Booking for ${data.code} send to ${data.phone}`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
async bookingExpired(data: WhatsappBookingCreate) {
|
||||||
|
const momentDate = moment(data.time);
|
||||||
|
const fallbackValue = momentDate.locale('id').format('dddd, DD MMMM YYYY');
|
||||||
|
// const dayOfWeek = momentDate.day();
|
||||||
|
// const dayOfMonth = momentDate.date();
|
||||||
|
// const year = momentDate.year();
|
||||||
|
// const month = momentDate.month() + 1;
|
||||||
|
// const hour = momentDate.hour();
|
||||||
|
// const minute = momentDate.minute();
|
||||||
|
|
||||||
|
const payload = {
|
||||||
|
messaging_product: 'whatsapp',
|
||||||
|
to: phoneNumberOnly(data.phone), // recipient's phone number
|
||||||
|
type: 'template',
|
||||||
|
template: {
|
||||||
|
name: 'booking_expired',
|
||||||
|
language: {
|
||||||
|
code: 'id', // language code
|
||||||
|
},
|
||||||
|
components: [
|
||||||
|
{
|
||||||
|
type: 'body',
|
||||||
|
parameters: [
|
||||||
|
{
|
||||||
|
type: 'text',
|
||||||
|
parameter_name: 'customer',
|
||||||
|
text: data.name, // replace with name variable
|
||||||
|
},
|
||||||
|
{
|
||||||
|
type: 'text',
|
||||||
|
parameter_name: 'code',
|
||||||
|
text: data.code, // replace with queue_code variable
|
||||||
|
},
|
||||||
|
{
|
||||||
|
type: 'text',
|
||||||
|
parameter_name: 'booking_date',
|
||||||
|
text: fallbackValue,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
const response = await this.sendMessage(payload);
|
||||||
|
if (response)
|
||||||
|
Logger.log(
|
||||||
|
`Notification register Booking for ${data.code} send to ${data.phone}`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
async rescheduleCreated(data: WhatsappBookingCreate) {
|
||||||
|
const imageUrl = `${BOOKING_QR_URL}${data.id}`;
|
||||||
|
|
||||||
|
const momentDate = moment(data.time);
|
||||||
|
const fallbackValue = momentDate.locale('id').format('dddd, DD MMMM YYYY');
|
||||||
|
// const dayOfWeek = momentDate.day();
|
||||||
|
// const dayOfMonth = momentDate.date();
|
||||||
|
// const year = momentDate.year();
|
||||||
|
// const month = momentDate.month() + 1;
|
||||||
|
// const hour = momentDate.hour();
|
||||||
|
// const minute = momentDate.minute();
|
||||||
|
|
||||||
|
const payload = {
|
||||||
|
messaging_product: 'whatsapp',
|
||||||
|
to: phoneNumberOnly(data.phone), // recipient's phone number
|
||||||
|
type: 'template',
|
||||||
|
template: {
|
||||||
|
name: 'reschedule_created',
|
||||||
|
language: {
|
||||||
|
code: 'id', // language code
|
||||||
|
},
|
||||||
|
components: [
|
||||||
|
{
|
||||||
|
type: 'header',
|
||||||
|
parameters: [
|
||||||
|
{
|
||||||
|
type: 'image',
|
||||||
|
image: {
|
||||||
|
link: imageUrl,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
type: 'body',
|
||||||
|
parameters: [
|
||||||
|
{
|
||||||
|
type: 'text',
|
||||||
|
parameter_name: 'customer',
|
||||||
|
text: data.name, // replace with name variable
|
||||||
|
},
|
||||||
|
{
|
||||||
|
type: 'text',
|
||||||
|
parameter_name: 'booking_code',
|
||||||
|
text: data.code, // replace with queue_code variable
|
||||||
|
},
|
||||||
|
{
|
||||||
|
type: 'text',
|
||||||
|
parameter_name: 'booking_date',
|
||||||
|
text: fallbackValue,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
type: 'button',
|
||||||
|
sub_type: 'url',
|
||||||
|
index: '0',
|
||||||
|
parameters: [
|
||||||
|
{
|
||||||
|
type: 'text',
|
||||||
|
text: data.id, // replace with dynamic URL
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
const response = await this.sendMessage(payload);
|
||||||
|
if (response)
|
||||||
|
Logger.log(
|
||||||
|
`Notification register Booking for ${data.code} send to ${data.phone}`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
async bookingRegister(
|
||||||
|
data: WhatsappBookingCreate,
|
||||||
|
total: number,
|
||||||
|
paymentUrl: string,
|
||||||
|
) {
|
||||||
|
const momentDate = moment(data.time);
|
||||||
|
const fallbackValue = momentDate.locale('id').format('dddd, DD MMMM YYYY');
|
||||||
|
|
||||||
|
const formattedTotal = new Intl.NumberFormat('id-ID', {
|
||||||
|
style: 'currency',
|
||||||
|
currency: 'IDR',
|
||||||
|
minimumFractionDigits: 0,
|
||||||
|
maximumFractionDigits: 0,
|
||||||
|
})
|
||||||
|
.format(total)
|
||||||
|
.replace('IDR', 'Rp');
|
||||||
|
|
||||||
|
const payload = {
|
||||||
|
messaging_product: 'whatsapp',
|
||||||
|
to: phoneNumberOnly(data.phone), // recipient's phone number
|
||||||
|
type: 'template',
|
||||||
|
template: {
|
||||||
|
name: 'booking_register',
|
||||||
|
language: {
|
||||||
|
code: 'id', // language code
|
||||||
|
},
|
||||||
|
components: [
|
||||||
|
{
|
||||||
|
type: 'body',
|
||||||
|
parameters: [
|
||||||
|
{
|
||||||
|
type: 'text',
|
||||||
|
parameter_name: 'customer',
|
||||||
|
text: data.name, // replace with name variable
|
||||||
|
},
|
||||||
|
{
|
||||||
|
type: 'text',
|
||||||
|
parameter_name: 'booking_date',
|
||||||
|
text: fallbackValue,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
type: 'text',
|
||||||
|
parameter_name: 'booking_code',
|
||||||
|
text: data.code,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
type: 'text',
|
||||||
|
parameter_name: 'total',
|
||||||
|
text: formattedTotal,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
type: 'button',
|
||||||
|
sub_type: 'url',
|
||||||
|
index: '0',
|
||||||
|
parameters: [
|
||||||
|
{
|
||||||
|
type: 'text',
|
||||||
|
text: paymentUrl, // replace with dynamic URL
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
const response = await this.sendMessage(payload);
|
||||||
|
if (response)
|
||||||
|
Logger.log(
|
||||||
|
`Notification register Booking for ${data.code} send to ${data.phone}`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
async bookingRescheduleOTP(data: WhatsappBookingCreate) {
|
||||||
|
const momentDate = moment(data.time);
|
||||||
|
const fallbackValue = momentDate.locale('id').format('dddd, DD MMMM YYYY');
|
||||||
|
|
||||||
|
const payload = {
|
||||||
|
messaging_product: 'whatsapp',
|
||||||
|
to: phoneNumberOnly(data.phone), // recipient's phone number
|
||||||
|
type: 'template',
|
||||||
|
template: {
|
||||||
|
name: 'booking_reschedule',
|
||||||
|
language: {
|
||||||
|
code: 'id', // language code
|
||||||
|
},
|
||||||
|
components: [
|
||||||
|
{
|
||||||
|
type: 'body',
|
||||||
|
parameters: [
|
||||||
|
{
|
||||||
|
type: 'text',
|
||||||
|
parameter_name: 'customer',
|
||||||
|
text: data.name, // replace with name variable
|
||||||
|
},
|
||||||
|
{
|
||||||
|
type: 'text',
|
||||||
|
parameter_name: 'booking_code',
|
||||||
|
text: data.code, // replace with queue_code variable
|
||||||
|
},
|
||||||
|
{
|
||||||
|
type: 'text',
|
||||||
|
parameter_name: 'booking_date',
|
||||||
|
text: fallbackValue,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
type: 'text',
|
||||||
|
parameter_name: 'otp',
|
||||||
|
text: data.code,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
type: 'button',
|
||||||
|
sub_type: 'copy_code',
|
||||||
|
index: '0',
|
||||||
|
parameters: [
|
||||||
|
{
|
||||||
|
type: 'coupon_code',
|
||||||
|
coupon_code: data.code,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
const response = await this.sendMessage(payload);
|
||||||
|
if (response)
|
||||||
|
Logger.log(
|
||||||
|
`Notification reschedule Booking for ${data.code} send to ${data.phone}`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
async sendOtpNotification(data: { phone: string; code: string }) {
|
async sendOtpNotification(data: { phone: string; code: string }) {
|
||||||
// Compose the WhatsApp message payload for OTP using Facebook WhatsApp API
|
// Compose the WhatsApp message payload for OTP using Facebook WhatsApp API
|
||||||
const payload = {
|
const payload = {
|
||||||
|
@ -162,6 +503,22 @@ export class WhatsappService {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async sendTemplateMessage(data: { phone: string; templateMsg: any }) {
|
||||||
|
const payload = {
|
||||||
|
messaging_product: 'whatsapp',
|
||||||
|
to: data.phone,
|
||||||
|
type: 'template',
|
||||||
|
template: data?.templateMsg,
|
||||||
|
};
|
||||||
|
|
||||||
|
const response = await this.sendMessage(payload);
|
||||||
|
if (response) {
|
||||||
|
Logger.log(
|
||||||
|
`OTP notification for template ${data.templateMsg} sent to ${data.phone}`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
async queueProcess(data: WhatsappQueue) {
|
async queueProcess(data: WhatsappQueue) {
|
||||||
const queueUrl = `${WHATSAPP_BUSINESS_QUEUE_URL}?id=${data.id}`;
|
const queueUrl = `${WHATSAPP_BUSINESS_QUEUE_URL}?id=${data.id}`;
|
||||||
const payload = {
|
const payload = {
|
||||||
|
|
45
yarn.lock
45
yarn.lock
|
@ -1239,6 +1239,13 @@
|
||||||
resolved "https://registry.yarnpkg.com/@types/node/-/node-14.18.63.tgz#1788fa8da838dbb5f9ea994b834278205db6ca2b"
|
resolved "https://registry.yarnpkg.com/@types/node/-/node-14.18.63.tgz#1788fa8da838dbb5f9ea994b834278205db6ca2b"
|
||||||
integrity sha512-fAtCfv4jJg+ExtXhvCkCqUKZ+4ok/JQk01qDKhL5BDDoS3AxKXhV5/MAVUZyQnSEd2GT92fkgZl0pz0Q0AzcIQ==
|
integrity sha512-fAtCfv4jJg+ExtXhvCkCqUKZ+4ok/JQk01qDKhL5BDDoS3AxKXhV5/MAVUZyQnSEd2GT92fkgZl0pz0Q0AzcIQ==
|
||||||
|
|
||||||
|
"@types/qrcode@^1.5.5":
|
||||||
|
version "1.5.5"
|
||||||
|
resolved "https://registry.yarnpkg.com/@types/qrcode/-/qrcode-1.5.5.tgz#993ff7c6b584277eee7aac0a20861eab682f9dac"
|
||||||
|
integrity sha512-CdfBi/e3Qk+3Z/fXYShipBT13OJ2fDO2Q2w5CIP5anLTLIndQG9z6P1cnm+8zCWSpm5dnxMFd/uREtb0EXuQzg==
|
||||||
|
dependencies:
|
||||||
|
"@types/node" "*"
|
||||||
|
|
||||||
"@types/qs@*":
|
"@types/qs@*":
|
||||||
version "6.9.15"
|
version "6.9.15"
|
||||||
resolved "https://registry.yarnpkg.com/@types/qs/-/qs-6.9.15.tgz#adde8a060ec9c305a82de1babc1056e73bd64dce"
|
resolved "https://registry.yarnpkg.com/@types/qs/-/qs-6.9.15.tgz#adde8a060ec9c305a82de1babc1056e73bd64dce"
|
||||||
|
@ -2861,6 +2868,11 @@ diff@^4.0.1:
|
||||||
resolved "https://registry.yarnpkg.com/diff/-/diff-4.0.2.tgz#60f3aecb89d5fae520c11aa19efc2bb982aade7d"
|
resolved "https://registry.yarnpkg.com/diff/-/diff-4.0.2.tgz#60f3aecb89d5fae520c11aa19efc2bb982aade7d"
|
||||||
integrity sha512-58lmxKSA4BNyLz+HHMUzlOEpg09FV+ev6ZMe3vJihgdxzgcwZ8VoEEPmALCZG9LmqfVoNMMKpttIYTVG6uDY7A==
|
integrity sha512-58lmxKSA4BNyLz+HHMUzlOEpg09FV+ev6ZMe3vJihgdxzgcwZ8VoEEPmALCZG9LmqfVoNMMKpttIYTVG6uDY7A==
|
||||||
|
|
||||||
|
dijkstrajs@^1.0.1:
|
||||||
|
version "1.0.3"
|
||||||
|
resolved "https://registry.yarnpkg.com/dijkstrajs/-/dijkstrajs-1.0.3.tgz#4c8dbdea1f0f6478bff94d9c49c784d623e4fc23"
|
||||||
|
integrity sha512-qiSlmBq9+BCdCA/L46dw8Uy93mloxsPSbwnm5yrKn2vMPiy8KyAskTF6zuV/j5BMsmOGZDPs7KjU+mjb670kfA==
|
||||||
|
|
||||||
dir-glob@^3.0.1:
|
dir-glob@^3.0.1:
|
||||||
version "3.0.1"
|
version "3.0.1"
|
||||||
resolved "https://registry.yarnpkg.com/dir-glob/-/dir-glob-3.0.1.tgz#56dbf73d992a4a93ba1584f4534063fd2e41717f"
|
resolved "https://registry.yarnpkg.com/dir-glob/-/dir-glob-3.0.1.tgz#56dbf73d992a4a93ba1584f4534063fd2e41717f"
|
||||||
|
@ -6363,6 +6375,11 @@ png-js@^1.0.0:
|
||||||
resolved "https://registry.yarnpkg.com/png-js/-/png-js-1.0.0.tgz#e5484f1e8156996e383aceebb3789fd75df1874d"
|
resolved "https://registry.yarnpkg.com/png-js/-/png-js-1.0.0.tgz#e5484f1e8156996e383aceebb3789fd75df1874d"
|
||||||
integrity sha512-k+YsbhpA9e+EFfKjTCH3VW6aoKlyNYI6NYdTfDL4CIvFnvsuO84ttonmZE7rc+v23SLTH8XX+5w/Ak9v0xGY4g==
|
integrity sha512-k+YsbhpA9e+EFfKjTCH3VW6aoKlyNYI6NYdTfDL4CIvFnvsuO84ttonmZE7rc+v23SLTH8XX+5w/Ak9v0xGY4g==
|
||||||
|
|
||||||
|
pngjs@^5.0.0:
|
||||||
|
version "5.0.0"
|
||||||
|
resolved "https://registry.yarnpkg.com/pngjs/-/pngjs-5.0.0.tgz#e79dd2b215767fd9c04561c01236df960bce7fbb"
|
||||||
|
integrity sha512-40QW5YalBNfQo5yRYmiw7Yz6TKKVr3h6970B2YE+3fQpsWcrbj1PzJgxeJ19DRQjhMbKPIuMY8rFaXc8moolVw==
|
||||||
|
|
||||||
postgres-array@~2.0.0:
|
postgres-array@~2.0.0:
|
||||||
version "2.0.0"
|
version "2.0.0"
|
||||||
resolved "https://registry.yarnpkg.com/postgres-array/-/postgres-array-2.0.0.tgz#48f8fce054fbc69671999329b8834b772652d82e"
|
resolved "https://registry.yarnpkg.com/postgres-array/-/postgres-array-2.0.0.tgz#48f8fce054fbc69671999329b8834b772652d82e"
|
||||||
|
@ -6464,6 +6481,15 @@ pure-rand@^6.0.0:
|
||||||
resolved "https://registry.yarnpkg.com/pure-rand/-/pure-rand-6.1.0.tgz#d173cf23258231976ccbdb05247c9787957604f2"
|
resolved "https://registry.yarnpkg.com/pure-rand/-/pure-rand-6.1.0.tgz#d173cf23258231976ccbdb05247c9787957604f2"
|
||||||
integrity sha512-bVWawvoZoBYpp6yIoQtQXHZjmz35RSVHnUOTefl8Vcjr8snTPY1wnpSPMWekcFwbxI6gtmT7rSYPFvz71ldiOA==
|
integrity sha512-bVWawvoZoBYpp6yIoQtQXHZjmz35RSVHnUOTefl8Vcjr8snTPY1wnpSPMWekcFwbxI6gtmT7rSYPFvz71ldiOA==
|
||||||
|
|
||||||
|
qrcode@^1.5.4:
|
||||||
|
version "1.5.4"
|
||||||
|
resolved "https://registry.yarnpkg.com/qrcode/-/qrcode-1.5.4.tgz#5cb81d86eb57c675febb08cf007fff963405da88"
|
||||||
|
integrity sha512-1ca71Zgiu6ORjHqFBDpnSMTR2ReToX4l1Au1VFLyVeBTFavzQnv5JxMFr3ukHVKpSrSA2MCk0lNJSykjUfz7Zg==
|
||||||
|
dependencies:
|
||||||
|
dijkstrajs "^1.0.1"
|
||||||
|
pngjs "^5.0.0"
|
||||||
|
yargs "^15.3.1"
|
||||||
|
|
||||||
qs@6.11.0:
|
qs@6.11.0:
|
||||||
version "6.11.0"
|
version "6.11.0"
|
||||||
resolved "https://registry.yarnpkg.com/qs/-/qs-6.11.0.tgz#fd0d963446f7a65e1367e01abd85429453f0c37a"
|
resolved "https://registry.yarnpkg.com/qs/-/qs-6.11.0.tgz#fd0d963446f7a65e1367e01abd85429453f0c37a"
|
||||||
|
@ -8070,7 +8096,7 @@ yargs-parser@21.1.1, yargs-parser@^21.0.1, yargs-parser@^21.1.1:
|
||||||
resolved "https://registry.yarnpkg.com/yargs-parser/-/yargs-parser-21.1.1.tgz#9096bceebf990d21bb31fa9516e0ede294a77d35"
|
resolved "https://registry.yarnpkg.com/yargs-parser/-/yargs-parser-21.1.1.tgz#9096bceebf990d21bb31fa9516e0ede294a77d35"
|
||||||
integrity sha512-tVpsJW7DdjecAiFpbIB1e3qxIQsE6NoPc5/eTdrbbIC4h0LVsWhnoa3g+m2HclBIujHzsxZ4VJVA+GUuc2/LBw==
|
integrity sha512-tVpsJW7DdjecAiFpbIB1e3qxIQsE6NoPc5/eTdrbbIC4h0LVsWhnoa3g+m2HclBIujHzsxZ4VJVA+GUuc2/LBw==
|
||||||
|
|
||||||
yargs-parser@^18.1.1:
|
yargs-parser@^18.1.1, yargs-parser@^18.1.2:
|
||||||
version "18.1.3"
|
version "18.1.3"
|
||||||
resolved "https://registry.yarnpkg.com/yargs-parser/-/yargs-parser-18.1.3.tgz#be68c4975c6b2abf469236b0c870362fab09a7b0"
|
resolved "https://registry.yarnpkg.com/yargs-parser/-/yargs-parser-18.1.3.tgz#be68c4975c6b2abf469236b0c870362fab09a7b0"
|
||||||
integrity sha512-o50j0JeToy/4K6OZcaQmW6lyXXKhq7csREXcDwk2omFPJEwUNOVtJKvmDr9EI1fAJZUyZcRF7kxGBWmRXudrCQ==
|
integrity sha512-o50j0JeToy/4K6OZcaQmW6lyXXKhq7csREXcDwk2omFPJEwUNOVtJKvmDr9EI1fAJZUyZcRF7kxGBWmRXudrCQ==
|
||||||
|
@ -8108,6 +8134,23 @@ yargs@15.3.1:
|
||||||
y18n "^4.0.0"
|
y18n "^4.0.0"
|
||||||
yargs-parser "^18.1.1"
|
yargs-parser "^18.1.1"
|
||||||
|
|
||||||
|
yargs@^15.3.1:
|
||||||
|
version "15.4.1"
|
||||||
|
resolved "https://registry.yarnpkg.com/yargs/-/yargs-15.4.1.tgz#0d87a16de01aee9d8bec2bfbf74f67851730f4f8"
|
||||||
|
integrity sha512-aePbxDmcYW++PaqBsJ+HYUFwCdv4LVvdnhBy78E57PIor8/OVvhMrADFFEDh8DHDFRv/O9i3lPhsENjO7QX0+A==
|
||||||
|
dependencies:
|
||||||
|
cliui "^6.0.0"
|
||||||
|
decamelize "^1.2.0"
|
||||||
|
find-up "^4.1.0"
|
||||||
|
get-caller-file "^2.0.1"
|
||||||
|
require-directory "^2.1.1"
|
||||||
|
require-main-filename "^2.0.0"
|
||||||
|
set-blocking "^2.0.0"
|
||||||
|
string-width "^4.2.0"
|
||||||
|
which-module "^2.0.0"
|
||||||
|
y18n "^4.0.0"
|
||||||
|
yargs-parser "^18.1.2"
|
||||||
|
|
||||||
yargs@^16.0.0:
|
yargs@^16.0.0:
|
||||||
version "16.2.0"
|
version "16.2.0"
|
||||||
resolved "https://registry.yarnpkg.com/yargs/-/yargs-16.2.0.tgz#1c82bf0f6b6a66eafce7ef30e376f49a12477f66"
|
resolved "https://registry.yarnpkg.com/yargs/-/yargs-16.2.0.tgz#1c82bf0f6b6a66eafce7ef30e376f49a12477f66"
|
||||||
|
|
Loading…
Reference in New Issue